Skip to content

Python break nested loop | Example code

  • by

A nested loop contains multiple loops, Using a break statement only breaks the inner loop, it only exits from the inner loop and the outer loop still continues.

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

Example breaking the 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 the 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 a break, set the flag to True, and in the outer loop, set break if the flag is 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 or suggestions on this Python Loop tutorial

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *