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

82,106

Solution 1

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).

Solution 2

while True:
    for i in xrange(10):
        if condition(i):
            break
    else:
        break

That will do what you seem to want. Why you would want to do it is a different matter. Maybe you should take a look at your code and make sure you're not missing an obvious and easier way to do it.

Solution 3

some action that resarts the whole process

A poor way to think of an algorithm.

You're just filtering, i.e., removing duplicates.

And -- in Python -- you're happiest making copies, not trying to do del. In general, there's very little call to use del.

def unique( some_list ):
    list_iter= iter(some_list)
    prev= list_iter.next()
    for item in list_iter:
        if item != prev:
            yield prev
            prev= item
    yield prev

list( unique( ['berry','||','||','||','pancake'] ) )

Solution 4

The inevitable itertools version, because it just came to me:

from itertools import groupby

def uniq(seq):
    for key, items in groupby(seq):
        yield key

print list(uniq(['berry','||','||','||','pancake'])) # ['berry','||', 'pancake']
# or simply:
print [key for key, items in groupby(['berry','||','||','||','pancake'])]

Solution 5

Continue will work for any loop.

Share:
82,106
Georgina
Author by

Georgina

Updated on July 09, 2022

Comments

  • Georgina
    Georgina almost 2 years

    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!