Can you "restart" the current iteration of a Python loop?

Question:

Is there a way to implement something like this:

for row in rows:
    try:
        something
    except:
        restart iteration
Asked By: user3063864

||

Answers:

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
Answered By: rafaelc

You could put your try/except block in another loop and then break when it succeeds:

for row in rows:
    while True:
        try:
            something
            break
        except Exception: # Try to catch something more specific
            pass
Answered By: user2555451

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
Answered By: Padraic Cunningham

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
Answered By: Sanke

Try this

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

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. That being said, performance is not a first order determinant in Python.

Answered By: keepAlive

Here is a simple version without using nested loops, an infinite while loop, or mutating the original iterator. Also, it controls the number of attempts with a max_retry parameter:

def do_something(retry=0, max_retry=4):
    try:
        print('something')
    except Exception as e:
        if retry == max_retry:
            print(f"Max retries reached!")
            raise e
        do_something(retry=retry + 1)

do_something()
Answered By: nocibambi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.