Break out from Nested Loops in Python

Python – Break out from Nested Loops

To break out of all the loops from an inner loop in Python, set a boolean flag in inner loop before break out, and then check this flag in all the outer loops as a condition to break out from them as well.

The following is a simple pseudo code snippet depicting the use of the break flag to break out of all outer loops from an inner loop.

Pseudo Code

breakFlag = False

for i in x:
    for j in y:
        for k in z:
            ...
            if some_condition_to_break_out_from_all_loops:
                breakFlag = True
                break
        if breakFlag:
            break
    if breakFlag:
        break

Example

In the following example, we will take a three level nested For Loop, and break out of all the loops form the inner most loop using a flag.

Python Program

breakFlag = False

for i in range(10):
    for j in range(i):
        for k in range(j):
            if i == 4 and j == 2 and k == 2:
                breakFlag = True
                break
            print('*', end='')
        if breakFlag:
            break
        print(' ', end='')
    if breakFlag:
        break
    print()
Run Code Copy

Output

 * 
 * ** 
 * ** *** 
 * ** *** **** 
 * ** *** **** ***** 
 * ** *** **** ***** ****** 
 * ** *** **** ***** ****** ******* 
 * ** *** **** ***** ****** ******* ******** 

References

Summary

In this tutorial of Python Examples, we learned how to break out from all the loops from an inner loop using a boolean flag and break statement, with detailed examples.

Code copied to clipboard successfully 👍