Skip to content
Kuza Ndoto Academy

Nested Loops

Beginner → IntermediateChapter 3 · Page 18 of 565 min readUpdated 15 Nov 2026

A nested loop is a loop inside another loop. The inner loop runs completely for every single pass of the outer loop. Nested loops are the natural tool for anything shaped like a grid: tables, seating plans, game boards and pairs of items.

How nested loops run

Read the code below slowly. The outer loop picks a value for row; then the inner loop runs all the way through for that row before the outer loop moves on.

for row in range(1, 3):
    for col in range(1, 4):
        print("row", row, "col", col)
    print("-- end of row", row)
row 1 col 1 row 1 col 2 row 1 col 3 -- end of row 1 row 2 col 1 row 2 col 2 row 2 col 3 -- end of row 2

The outer loop runs 2 times and the inner loop runs 3 times per outer pass, so the innermost print() runs 2 × 3 = 6 times. The print("-- end of row", row) line is indented only once, so it belongs to the outer loop and runs after each inner loop finishes.

col 1 col 2 col 3 row 1 row 2 1row 1 col 1 2row 1 col 2 3row 1 col 3 4row 2 col 1 5row 2 col 2 6row 2 col 3 outer loop: 2 passes inner loop: 3 per pass total: 2 × 3 = 6
Figure 1. The big numbers show the order in which the innermost print() runs. The inner loop finishes a whole row before the outer loop moves to the next row.

Printing a multiplication table

Using end="" keeps the inner loop's output on one line, and an empty print() after the inner loop starts the next row. The format specifier :4 in the f-string pads each number to 4 characters wide so the columns line up.

for i in range(1, 5):
    for j in range(1, 5):
        print(f"{i * j:4}", end="")
    print()      # move to the next line
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16

Drawing patterns

Patterns are a classic way to practise nested loops. Here the inner loop's range depends on the outer loop's variable, so each row is longer than the last.

for row in range(1, 5):
    for star in range(row):
        print("*", end="")
    print()
* ** *** ****

(In real code, print("*" * row) does the same job in one loop, but the nested version shows how the inner range can change on every outer pass.)

Working with pairs

Nested loops can combine every item of one collection with every item of another. This prints every home-and-away fixture for three football teams, skipping a team playing itself:

teams = ["Gor Mahia", "AFC Leopards", "Tusker"]

for home in teams:
    for away in teams:
        if home != away:
            print(home, "vs", away)
Gor Mahia vs AFC Leopards Gor Mahia vs Tusker AFC Leopards vs Gor Mahia AFC Leopards vs Tusker Tusker vs Gor Mahia Tusker vs AFC Leopards

Looping through a grid (a list of lists)

A list can contain other lists. Each inner list can represent a row, which makes a grid. The outer loop takes one row at a time, and the inner loop takes each item in that row.

seats = [
    ["A1", "A2", "A3"],
    ["B1", "B2", "B3"],
    ["C1", "C2", "C3"],
]

for row in seats:
    for seat in row:
        print(seat, end=" ")
    print()
A1 A2 A3 B1 B2 B3 C1 C2 C3

This pattern also works for adding up a table of numbers, such as a week of sales for each mama mboga stall in a market.

sales = [
    [1200, 900, 1500],    # stall 1, three days
    [800, 1100, 950],     # stall 2
]
grand_total = 0

for stall in sales:
    for amount in stall:
        grand_total += amount

print("Grand total: KES", grand_total)
Grand total: KES 6450

Breaking out of nested loops

break only leaves the loop it's directly inside (see Break, Continue & Pass). To stop both loops, a common approach is a flag variable that the outer loop checks.

grid = [
    [3, 8, 1],
    [6, 0, 4],
    [7, 2, 0],
]
found = False

for r, row in enumerate(grid):
    for c, value in enumerate(row):
        if value == 0:
            print("First zero at row", r, "column", c)
            found = True
            break          # leaves the inner loop
    if found:
        break              # leaves the outer loop
First zero at row 1 column 1

A cleaner alternative is to put the loops inside a function and use return, which exits everything at once. You'll learn that on Return Values.

Warning

Nested loops multiply the work. Two loops over 1,000 items each run the inner block 1,000,000 times, which can make a program noticeably slow. Before nesting loops over large data, ask whether a set or dictionary lookup could avoid the inner loop.

Common mistake

Getting the indentation of the "end of row" print() wrong. Indent it once and it runs after each row; indent it twice and it runs after every single item; don't indent it and it runs only once, after both loops have finished. Also, use different variable names for the inner and outer loops, such as i and j, never the same name twice.

Key points

  • The inner loop runs completely for every pass of the outer loop, so total runs = outer × inner.
  • Nested loops suit grids, tables, patterns and pairs of items.
  • Use end="" and an empty print() to build rows of output.
  • break exits only the inner loop; use a flag or a function's return to exit both.
  • Watch performance: nested loops over big collections get slow quickly.
Up next · New chapter: Data StructuresListsOrdered, changeable collections of items.
→

Tip: use the ← and → keys to move between pages.