Python – Way to restart a for loop, similar to “continue” for while loops? [duplicate]

Posted on

Question :

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.


Asked By: Georgina


Answer #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:
  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

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

Answered By: Georgina

Answer #2:

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

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.

Answered By: Liquid_Fire

Answer #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)
    for item in list_iter:
        if item != prev:
            yield prev
            prev= item
    yield prev

list( unique( ['berry','||','||','||','pancake'] ) )
Answered By: nmichaels

Answer #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'])]
Answered By: S.Lott

Answer #5:

Continue will work for any loop.

Answered By: Jochen Ritzel

Answer #6:

continue works in for loops also.

>>> for i in range(3):
...     print 'Before', i
...     if i == 1:
...             continue
...     print 'After', i
Before 0
After 0
Before 1
# After 1 is missing
Before 2
After 2
Answered By: volting

Answer #7:

As you can see answering your question leads to some rather convoluted code. Usually a better way can be found, which is why such constructs aren’t built into the language

If you are not comfortable using itertools, consider using this loop instead. Not only is it easier to follow than your restarting for loop, it is also more efficient because it doesn’t waste time rechecking items that have already been passed over.

L = ['berry','||','||','||','pancake']
while idx<len(L):
    if L[idx-1]==L[idx]:
        del L[idx]
Answered By: Sam Dolan

Answer #8:

def remove_adjacent(nums):
     return [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]

example = ['berry','||','||','||','pancake']

example = remove_adjacent(example)
print example
""" Output:
['berry', '||', 'pancake']

And by the way this is repeating of Remove adjacent duplicate elements from a list

Answered By: John La Rooy

Leave a Reply

Your email address will not be published. Required fields are marked *