Python Nested Loops · Examples
Beginner

Python Nested Loops Examples

Short, runnable programs that show python nested loops in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Nested Loops lesson.

1A times table grid with headings

The first loop prints the column headings, then a nested loop prints each row: a heading, followed by the products. :4 pads each number to four characters so everything lines up.

A times table grid with headings
print("    ", end="")
for col in range(1, 5):
    print(f"{col:4}", end="")
print()
for row in range(1, 5):
    print(f"{row:4}", end="")
    for col in range(1, 5):
        print(f"{row * col:4}", end="")
    print()
Expected output       1   2   3   4
   1   1   2   3   4
   2   2   4   6   8
   3   3   6   9  12
   4   4   8  12  16

2A pyramid of characters

Each row prints some spaces first, then an odd number of # characters. Both counts depend on the outer variable, so the inner loop does a different amount of work on every row.

A pyramid of characters
height = 4
for row in range(1, height + 1):
    print(" " * (height - row), end="")
    for _ in range(2 * row - 1):
        print("#", end="")
    print()
Expected output   #
  ###
 #####
#######

3Every size with every colour

Two loops over two different lists produce every combination exactly once. The counter shows the total is 3 x 3 = 9.

Every size with every colour
sizes = ["S", "M", "L"]
colors = ["red", "blue", "green"]
count = 0
for size in sizes:
    for color in colors:
        count += 1
        print(f"{count}. {size} {color} t-shirt")
print("Total variations:", count)
Expected output1. S red t-shirt
2. S blue t-shirt
3. S green t-shirt
4. M red t-shirt
5. M blue t-shirt
6. M green t-shirt
7. L red t-shirt
8. L blue t-shirt
9. L green t-shirt
Total variations: 9

4Counting free seats in a seating chart

A list of lists is a grid: the outer loop takes one row of seats, the inner loop looks at each seat in it. A single counter lives outside both loops.

Counting free seats in a seating chart
seats = [
    ["taken", "taken", "free"],
    ["taken", "free", "taken"],
    ["free", "free", "taken"],
]
free_count = 0
for row in seats:
    for seat in row:
        if seat == "free":
            free_count += 1
print("Free seats:", free_count)
Expected outputFree seats: 4

5Every pair of guests exactly once

To pair items from the same list without repeats, start the inner loop just after the outer position with range(i + 1, ...). That skips pairing a guest with themselves and avoids shaking the same two hands twice.

Every pair of guests exactly once
guests = ["Asha", "Ben", "Chen", "Dia"]
handshakes = 0
for i in range(len(guests)):
    for j in range(i + 1, len(guests)):
        print(guests[i], "shakes hands with", guests[j])
        handshakes += 1
print("Handshakes:", handshakes)
Expected outputAsha shakes hands with Ben
Asha shakes hands with Chen
Asha shakes hands with Dia
Ben shakes hands with Chen
Ben shakes hands with Dia
Chen shakes hands with Dia
Handshakes: 6

6A checkerboard pattern

The sum row + col is even on one colour of square and odd on the other, so a simple remainder test decides which character to draw.

A checkerboard pattern
for row in range(4):
    for col in range(8):
        if (row + col) % 2 == 0:
            print("#", end="")
        else:
            print(".", end="")
    print()
Expected output#.#.#.#.
.#.#.#.#
#.#.#.#.
.#.#.#.#

Practise next

Python Nested Loops exercises → Back to the lesson

Python for Loops examplesPython range() Function examplesPython Lists examples