2

How can I do this in python:

x = [1,2,3,4,5,6]
for i in x:
    if i == 4:
       -restart the loop from beginning-
    else:
        print i

So here it will print till 4 then repeat the loop

9
  • what do you mean by 'repeat'? do you mean print (1,2,3,4,1,2,3,4) etc.? Commented Jan 10, 2014 at 14:43
  • 1
    I would use a recursive function defining the loop as a function Commented Jan 10, 2014 at 14:44
  • I would use itertools.cycle. Commented Jan 10, 2014 at 14:45
  • Take a look at this answer, second option Commented Jan 10, 2014 at 14:46
  • 1
    What would be the purpose of that? Why not just do while True: for i in range(1, 5):? Commented Jan 10, 2014 at 14:46

6 Answers 6

10

What about this:

x = [1,2,3,4,5,6]
restart = True
while restart:
    for i in x:
        # add any exit condition!
        # if foo == bar:
        #   restart = False
        #   break
        if i == 4:
           break
        else:
            print i
Sign up to request clarification or add additional context in comments.

1 Comment

Could also put print i before the if statement, and remove else
2

Something like this perhaps? But it will loop forever...

x = [ ..... ]
restart = True
while restart:
    for i in x:
        if i == 4:
            restart = True
            break
        restart = False
        print i

Comments

2

You can't directly. Use itertools.cycle

for idx, val in enumerate(itertools.cycle(range(4))):
    print v
    if idx>20:
        break

idx is used to break infiniteloop

Comments

0

Just wrap in a while statement.

while True:
    restart = False
    for i in x:
        if i == 4:
            restart = True
            break
        else:
            print i
    if not restart:
        break

Comments

0

With a while loop:

x=[1,2,3,4,5,6]
i=0
while i<len(x): 
    if x[i] == 4:
        i=0
        continue
    else:
        print x[i]
    i+=1

Comments

-3

I would use a recursive function for that

def fun(x):
    for i in x:
        if i == 4:
            fun(x)
        else:
            print i
    return;

x = [1,2,3,4,5,6]
fun(x)

5 Comments

You're going to get a RuntimeError for exceeding the maximum recursion limit very quickly. The default is 1000.
How many times does author want to repeat?
recursive functions are dangerous for high values of recursion, and are a lot hard to integrate exit conditions into.
ok, I agree, I remove the post than?
You click delete @freude

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.