Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Way to restart a for loop, similar to "continue" for while loops? [duplicate]

Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.

What I'm trying to do is this:

    for index, item in enumerate(list2):
    if item == '||' and list2[index-1] == '||':
        del list2[index]
        *<some action that resarts the whole process>*

That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:

['berry','||','pancake'] instead.

Thanks!

like image 656
Georgina Avatar asked Sep 13 '10 22:09

Georgina


People also ask

How do you repeat a loop again in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do you start a while loop over again?

Note. You use the continue statement to restart a loop such as the while loop, for loop or for-in loop. If there are nested loops, the continue statement will restart the innermost loop.

How do you restart a nested while loop in Python?

You can use the input() function to restart a while loop in Python. And use the if statement to restart loop count.


1 Answers

I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?

If it's the latter, then for loops support continue just like while loops do:

for i in xrange(10):
  if i == 5:
    continue
  print i

The above will print the numbers from 0 to 9, except for 5.

If you're talking about starting over from the beginning of the for loop, there's no way to do that except "manually", for example by wrapping it in a while loop:

should_restart = True
while should_restart:
  should_restart = False
  for i in xrange(10):
    print i
    if i == 5:
      should_restart = True
      break

The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).

like image 64
Liquid_Fire Avatar answered Sep 28 '22 01:09

Liquid_Fire