How to continue in nested loops in Python
You use break
to break out of the inner loop and continue with the parent
for a in b:
for c in d:
if somecondition:
break # go back to parent loop
Here's a bunch of hacky ways to do it:
Create a local function
for a in b: def doWork(): for c in d: for e in f: if somecondition: return # <continue the for a in b loop?> doWork()
A better option would be to move doWork somewhere else and pass its state as arguments.
Use an exception
class StopLookingForThings(Exception): pass for a in b: try: for c in d: for e in f: if somecondition: raise StopLookingForThings() except StopLookingForThings: pass
- Break from the inner loop (if there's nothing else after it)
- Put the outer loop's body in a function and return from the function
- Raise an exception and catch it at the outer level
- Set a flag, break from the inner loop and test it at an outer level.
- Refactor the code so you no longer have to do this.
I would go with 5 every time.
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break