Skip to content Skip to sidebar Skip to footer

Can You "restart" The Current Iteration Of A Python Loop?

Is there a way to implement something like this: for row in rows: try: something except: restart iteration

Solution 1:

You could make rows an iterator and only advance when there is no error.

it = iter(rows)  
row = next(it,"")
while row:
    try:
        something
        row = next(it,"")
    except:
       continue

On a side note, if you are not already I would catch specific error/errors in the except, you don't want to catch everything.

If you have Falsey values you could use object as the default value:

it = iter(rows)
row, at_end = next(it,""), object()
while row is not at_end:
    try:
        something
        row = next(it, at_end)
    except:
        continue

Solution 2:

Although I wouldn't recommend that, the only way to do this is to make a While (True) Loop until it gets something Done.

Bear in mind the possibility of a infinite loop.

for row in rows:
    try:
        something
    except:
        flag = False
        while not flag:
            try: 
               something
               flag = True
            except:
               pass

Solution 3:

Have your for loop inside an infinite while loop. Check the condition where you want to restart the for loop with a if else condition and break the inner loop. have a if condition inside the while loop which is out side the for loop to break the while loop. Like this:

    while True:
      for row in rows:
        if(condition)
        .....
        if(condition)
         break
   if(condition)
     break

Solution 4:

Try this

it = iter(rows)
while True:
    try:
        something
        row = next(it)        
    except StopIteration:
        it = iter(rows)

Solution 5:

My 2¢, if rows is a list, you could do

for row in rows:
    try:
        something
    except:
        # Let's restart the current iteration
        rows.insert(rows.index(row), row)
        continue  # <-- will skip `something_else`, i.e will restart the loop.

    something_else
    

Also, other things being equal, for-loops are faster than while-loops in Python.


Post a Comment for "Can You "restart" The Current Iteration Of A Python Loop?"