Double for loop Python | Example code

In Python, you can simply use a loop inside the loop to get double loops. In Double-loop The “inner loop” will be executed one time for each iteration of the “outer loop”.

for iterating_var in sequence:

   for iterating_var in sequence:

      statements(s)

   statements(s)

Python Double for loop example

Simple example code

num = [1, 2, 3]
fruits = ["Apple", "Banana"]

for x in num:
    for y in fruits:
        print(x, y)

Output:

Double for loop Python

How to exit a double loop in python?

Answer: Use the break keyword to break the double loop. When the break is executed in the inner loop, it only exits from the inner loop and the outer loop still continues.

l1 = [1, 2, 3]
l2 = [10, 20]

for i in l1:
    for j in l2:
        print(i, j)
        if i == 2 and j == 20:
            print('BREAK')
            break

Output:

1 10
1 20
2 10
2 20
BREAK
3 10
3 20

Breaking out of two loops example

for i in range(1, 3):
    for j in range(1, 5):
        print(i, j)

        if i == j:
            print("Break All loops")
            break
    else:
        continue
    break

Output:

1 1
Break All loops

Do comment if you have any doubts and suggestions on this Python loop topic.

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.