How to break a for loop in Python?


In Python normally for loops are constructed to iterate over a block for each item in a range. If a premature termination of loop is sought before all iterations are completed, then we can use break keyword. It is invariably used in a conditional statement inside the body of a loop.

Using the break statement

Let’s take a few examples to see how the break statement works on for loops.

Example

In this example the for loop is defined to iterate upto 20 loops, but the break statement terminates the for loop at 10th iteration i.e., x=10.

If we apply a break statement to the inner loop of a nested for loop then it will break only for that innermost loop. It doesn’t stop the entire loop.

for x in range(20): 
    print (x) 
    if x==10: 
        break 
        print ("end of loop")

Output

0
1
2
3
4
5
6
7
8
9
10 

Example

In this example the inner loop stopped at i = 0 and j = 2 iteration so that the loop skipped the remaining 2 iterations (0, 3) and (0,4). We can use flag variable to stop the entire loop at particular iterations. Let’s see an example below.

for i in range(5):
    for j in range(5):
        print(i,j)
        if i == 0 and j == 2:
            print("stopping the inner loop at i = 0 and j = 2")
            break

Output

0 0
0 1
0 2
stopping the inner loop at i = 0 and j = 2
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4

Example

The flag variable terminated the nested loop at (0,2) iteration.

flag = False
for i in range(5):
    for j in range(5):
        print(i,j)
        if i == 0 and j == 2:
            print("stopping the loops at i = 0 and j = 2")
            flag = True
            break
    if flag:
        break

Output

0 0
0 1
0 2
stopping the loops at i = 0 and j = 2

Using the return statement

To break a for loop we can use return keyword, here we need to place the loop in a function. Using a return keyword can directly end the function.

Example

The return keyword terminated the nested for loop at (0,2)th iteration.

def check():
    for i in range(5):
        for j in range(5):
            print(i,j)
            if i == 0 and j == 2:
                return "stopping the loops at i = 0 and j = 2"

print(check())   

Output

0 0
0 1
0 2
stopping the loops at i = 0 and j = 2

Updated on: 23-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements