Skip to content

Python nested loop | Example code

When you define the one loop inside the other loop is called a Nested loop in Python. The “inner loop” will be executed one time for each iteration of the “outer loop”:

Note: The outer loop can contain any number of the inner loop. There is no limitation on the nesting of loops.

Python nested loop example

Simple example codes each iteration of an outer loop the inner loop re-start and completes its execution before the outer loop can continue to its next iteration.

color = ["Red", "Green", "Black"]
num = [1, 2, 3]

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

Output:

Python nested loop

Nested Loop to Print Pattern

rows = 5
# outer loop
for i in range(1, rows + 1):
    # inner loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')

Output:

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

Break Nested loop

Use the break statement inside the loop to exit out of the loop. If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.

for i in range(4):
    for j in range(4):
        if j == i:
            break
        print(i, j)

Output:

1 0
2 0
2 1
3 0
3 1
3 2

Continue Nested loop

Use the continue statement to skip the current iteration and move to the next iteration. It skips all the statements below it and immediately jumps to the next iteration.

for i in range(2):
    for j in range(2):
        if j == i:
            print("Skip")
            continue
        print(i, j)

Output:

Skip
0 1
1 0
Skip

How to Single Line Nested Loops?

Answer: Using List Comprehension get all combinations of 2 lists.

first = [2, 3, 4]
second = [1, 0, 5]

final = [i + j for i in first for j in second]

print(final)

Output: [3, 2, 7, 4, 3, 8, 5, 4, 9]

Please comment if you have any doubts or suggestions on this Python loop topic.

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.

1 thought on “Python nested loop | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading