Python break nested loop | Example code

Nested looop contain the multiple loops, Using a break statement only break the inner loop, it only exits from the inner loop and the outer loop still continues.

But we can use else block with continue keyword or flag variable to break nested loop in Python.

Example breaking only inner loop.

list1 = [1, 2, 3]
list2 = ["A", "B", "C"]

for i in list1:
    for j in list2:
        print(i, j)
        if i == 2 and j == "B":
            print('BREAK')
            break

Output:

1 B
1 C
2 A
2 B
BREAK
3 A
3 B
3 C

Example break nested loop in Python

Simple example code.

Using else block with continue

Get out of all the loops from inside.

list1 = [1, 2, 3]
list2 = ["A", "B", "C"]

for i in list1:
    for j in list2:
        print(i, j)
        if i == 2 and j == "B":
            print('BREAK')
            break
    else:
        continue
    break

Output:

Python break nested loop

Add a flag variable

In the condition that the inner loop ends with break, set the flag to True, and in the outer loop, set break if flag true.

list1 = [1, 2, 3]
list2 = ["A", "B", "C"]

flag = False
for i in list1:
    for j in list2:
        print(i, j)
        if i == 2 and j == "B":
            flag = True
            print('BREAK')
            break
    if flag:
        break

Output:

1 A
1 B
1 C
2 A
2 B
BREAK

Do comment if you have any doubts and suggestions on this Python Loop tutoiral

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.