1

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

Mero
  • 1,280
  • 4
  • 15
  • 25
  • what do you mean by 'repeat'? do you mean print (1,2,3,4,1,2,3,4) etc.? – Corley Brigman Jan 10 '14 at 14:43
  • 1
    I would use a recursive function defining the loop as a function – freude Jan 10 '14 at 14:44
  • I would use [`itertools.cycle`](http://docs.python.org/2/library/itertools.html#itertools.cycle). – kojiro Jan 10 '14 at 14:45
  • Take a look at [this answer](http://stackoverflow.com/questions/3704918/python-way-to-restart-a-for-loop-similar-to-continue-for-while-loops), second option – Andrei Jan 10 '14 at 14:46
  • 1
    What would be the purpose of that? Why not just do `while True: for i in range(1, 5):`? – Joel Cornett Jan 10 '14 at 14:46
  • For context, is there a language you *can* do this in? I mean, restart a loop at the beginning of an iterable object using a foreach-type syntax? (Obviously you can do it if you're looping over indices.) – kojiro Jan 10 '14 at 14:49
  • Sorry if it sound bit confusing. It is a part of my code. The main idea is that while I am looping if I detected an **X** variable I want to restart the loop from beginning – Mero Jan 10 '14 at 14:50
  • @Meran: What will be your exit condition? Or do you plan on looping forever? – Joel Cornett Jan 10 '14 at 14:53
  • @JoelCornett No i don't want to loop for ever – Mero Jan 10 '14 at 14:56

6 Answers6

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
sphere
  • 1,330
  • 13
  • 24
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
Ford
  • 2,559
  • 1
  • 22
  • 27
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

volcano
  • 3,578
  • 21
  • 28
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
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32
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
JPG
  • 2,224
  • 2
  • 15
  • 15
-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)
freude
  • 3,632
  • 3
  • 32
  • 51