What is the best way to repeat the current iteration of a loop without going to the next iteration?

112 Views Asked by At

Sometimes inside a for loop I would like to be able to repeat the current iteration from the beginning, something like that:

for element in list:
    # top of for
    ...
    if condition:
        ...
        repeat # that would make the current iteration restart from the top
               # without getting the next element in the list

I usually emulate this behavior with a while inside a for:

for element in list:
    while True:
        # top of while=top of for 
        ...
        if condition:
            ...
            continue # repeat: go to the top of the while
        ...
        # last line inside the while will break the while 
        break

Is there a nicer way to do that?

1

There are 1 best solutions below

0
Matan Benita On

If this is possible I would put the nested loop inside of a private function. that would be more clear. another option is to iterate the list

iter_list = iter(list)
value = next(iter_list,None)
while value is not None: # you reached the end of the iterator
    ....
    if not condition:
        value = next(iter_list,None)
        continue # condition isn't met skip to the next item