How to Break out of multiple loops in Python
Published on Aug. 22, 2023, 12:15 p.m.
There are several ways to break out of multiple nested loops in Python:
- Add a flag variable and set it when you want to break out of all loops:
done = False
for i in range(10):
for j in range(5):
if i+j == 12:
done = True
break
if done:
break
- Use the
return
statement to exit from a function that contains the loops:
def my_function():
for i in range(10):
for j in range(5):
if i+j == 12:
return
- Raise an exception and catch it outside the loops:
class BreakIt(Exception):
pass
try:
for i in range(10):
for j in range(5):
if i+j == 12:
raise BreakIt
except BreakIt:
pass
- Use the
itertools.product()
function to avoid nested loops:
import itertools
for i, j in itertools.product(range(10), range(5)):
if i+j == 12:
break
Note that breaking out of nested loops may not be the best solution for your problem, so you should carefully consider if it is the right choice for your specific use case.