CodeMIRAI
0 XP

Nested loops

2 min read 5 runnable examples Quiz included

A nested loop is a loop inside another loop. For each round of the outer loop, the inner loop runs all the way through.

Python
for row in range(1, 4):
    for col in range(1, 4):
        print(f"({row},{col})", end=" ")
    print()      # new line after each row

The outer loop runs 3 times, and each time the inner loop runs 3 times: 9 pairs in total.

A multiplication grid

Python
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:4}", end="")
    print()

Printing patterns

Pattern problems are a classic way to practise nested loops:

Python
height = 5
for row in range(1, height + 1):
    print("*" * row)

print()

for row in range(1, height + 1):
    spaces = " " * (height - row)
    stars = "*" * (2 * row - 1)
    print(spaces + stars)

The second pattern uses string multiplication instead of an inner loop, which is shorter and just as clear.

Comparing every pair

Nested loops can compare items with each other:

Python
names = ["Asha", "Leo", "Mei", "Raj"]
for i in range(len(names)):
    for j in range(i + 1, len(names)):
        print(names[i], "vs", names[j])

Starting the inner loop at i + 1 avoids comparing someone with themselves and avoids repeating pairs.

Breaking out of nested loops

break only leaves the innermost loop. To stop everything, a function with return is the cleanest tool:

Python
def find_pair(numbers, target):
    for a in numbers:
        for b in numbers:
            if a + b == target and a != b:
                return a, b
    return None

print(find_pair([3, 8, 11, 5, 2], 13))

Watch the cost

If the outer loop runs n times and the inner loop also runs n times, the body runs n × n times. For 1,000 items that's a million steps. It is fine for small data, but it is worth remembering when your data grows.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.