Python Loops · Lesson 37 of 149

Python Nested Loops

What you will learn

  • How a loop inside a loop works, and how many times the inner block runs
  • Printing tables and patterns
  • Going through the rows and columns of a grid
  • Making pairs and combinations
  • break and continue in nested loops, and the tool itertools.product

1. A loop inside a loop

A loop's block can contain another loop. The inner loop starts afresh and runs completely for each pass of the outer loop:

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

Follow it:

  1. The outer loop sets i = 1. The inner loop runs j = 1, 2, 3, printing 1 2 3 on one line (because of end="").
  2. The inner loop finishes, and the lone print() (indented under the outer loop) ends the line.
  3. The outer loop sets i = 2, and the inner loop starts again from j = 1.

Notice where the lines are indented: print() lines up with for j, so it runs once per outer pass. {i * j:3} shows each number in a width of 3 (lesson 4.5).

Quick check: with `range(3)` outside and `range(4)` inside, how many times does the inner block run?

12 times: 3 outer passes, with 4 inner passes in each.

2. Counting the passes

The inner block runs outer count × inner count times:

count = 0
for i in range(1, 4):
    for j in range(1, 4):
        count += 1
print("inner block ran", count, "times")
inner block ran 9 times

This matters for speed. A loop over n items inside a loop over n items does about n × n steps: ten items give a hundred steps, but ten thousand items give a hundred million. If a program is slow, a nested loop is the first thing to look at.

3. Patterns

The inner loop can depend on the outer variable. Triangles are the classic:

for i in range(1, 5):
    print("*" * i)
*
**
***
****

Here one loop was enough, because "*" * i repeats a string (lesson 4.1). With a second loop, the same triangle is written like this:

for i in range(1, 5):
    for j in range(i):
        print("*", end="")
    print()

The inner loop runs i times, so the rows grow. And a pyramid centres each row with spaces:

for i in range(1, 5):
    print(" " * (4 - i) + "*" * (2 * i - 1))
   *
  ***
 *****
*******

A checkerboard uses the sum of the two counters to alternate:

for i in range(3):
    row = ""
    for j in range(3):
        row += "#" if (i + j) % 2 == 0 else "."
    print(row)
#.#
.#.
#.#

(The # or . is chosen with a conditional expression, lesson 5.4.)

4. Rows and columns of a grid

A grid (a list of lists) needs a loop for the rows and a loop for the values in each row. Lists of lists are covered in chapter 7:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for value in row:
        print(value, end=" ")
    print()
1 2 3 
4 5 6 
7 8 9 

Totalling every value:

total = 0
for row in matrix:
    for value in row:
        total += value
print(total)
45

If you need the positions, loop over indexes. Here only the diagonal values, where the row number equals the column number, are printed:

for r in range(len(matrix)):
    for c in range(len(matrix[r])):
        if r == c:
            print(matrix[r][c], end=" ")
print()
1 5 9 

(matrix[r][c] means "row r, then column c".)

5. Pairs and combinations

Two loops over the same list give every pair. Add a condition to keep each unordered pair once:

nums = [1, 2, 3]
pairs = []
for a in nums:
    for b in nums:
        if a < b:
            pairs.append((a, b))
print(pairs)
[(1, 2), (1, 3), (2, 3)]

Two loops over different lists give every combination, such as every colour in every size:

colors = ["red", "blue"]
sizes = ["S", "M", "L"]
for c in colors:
    for s in sizes:
        print(c + "-" + s, end=" ")
print()
red-S red-M red-L blue-S blue-M blue-L 

6. break and continue in nested loops

break and continue act on the innermost loop only (lesson 6.3):

for x in range(2, 5):
    for y in range(2, 5):
        if x == y:
            continue
        print(x, y, end=" ")
print()
2 3 2 4 3 2 3 4 4 2 4 3 

continue skipped the pairs where x and y were equal. To leave both loops, use a flag or a function (lesson 6.3).

7. while inside while

Loops of different kinds can be nested. With while you must reset the inner counter yourself, for every outer pass:

i = 0
while i < 2:
    j = 0
    while j < 2:
        print(f"({i},{j})", end=" ")
        j += 1
    i += 1
print()
(0,0) (0,1) (1,0) (1,1) 

If j = 0 were placed before the outer loop, the inner loop would run only on the first pass. A for loop resets itself, which is one reason it is the easier choice.

8. A shortcut: itertools.product

Instead of nesting loops, itertools.product gives all combinations in one loop. And itertools.combinations gives unordered pairs (the standard library is chapter 17):

import itertools

print(list(itertools.product([1, 2], "ab")))
print(list(itertools.combinations([1, 2, 3], 2)))
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
[(1, 2), (1, 3), (2, 3)]

Worked example: seats in a small hall

A hall has 3 rows and 4 seats per row. Make every seat label, such as A1, and count the seats.

rows = "ABC"
labels = []
for row in rows:
    for seat in range(1, 5):
        labels.append(f"{row}{seat}")
print(labels)
print(len(labels))
['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'C3', 'C4']
12
Part What it does
outer loop over "ABC" one pass per row letter
inner loop over range(1, 5) seats 1 to 4 in that row
f"{row}{seat}" builds a label
len(labels) 3 × 4 = 12 seats

The hall is made up for the example.

Common mistakes

  • Indenting the line break wrongly. print() belongs under the outer loop, not the inner one.
  • Forgetting to reset the inner counter in nested while loops.
  • Using the same variable name for both loops (for i ... for i ...), which spoils the outer loop.
  • Not noticing how many passes there are. Two loops of 1000 make a million steps.
  • Expecting break to leave both loops.

Key takeaways

  • The inner loop runs completely for every pass of the outer loop; the inner block runs outer × inner times.
  • The indentation shows which lines belong to which loop.
  • Nested loops build tables, patterns, grids, pairs and combinations.
  • break and continue affect only the innermost loop; in nested while loops, reset the inner counter each time.
  • itertools.product replaces nested loops when you want every combination; watch the cost of big nests.

Practice

1. How many times does print("x") run: for i in range(4): then for j in range(5): then print("x")?

Show answer

20 times (4 × 5).

2. Write loops that print the triangle 1, 12, 123, 1234 (each on its own line).

Show answer
for i in range(1, 5):
    for j in range(1, i + 1):
        print(j, end="")
    print()

3. Print every pair (a, b) with a in [1, 2] and b in [10, 20].

Show answer
for a in [1, 2]:
    for b in [10, 20]:
        print(a, b)

This prints 1 10, 1 20, 2 10, 2 20.

4. Total the values in [[1, 2], [3, 4], [5]] with two loops.

Show answer
total = 0
for row in [[1, 2], [3, 4], [5]]:
    for value in row:
        total += value

total is 15.

5. What goes wrong if j = 0 is written before the outer while loop in the nested while example?

Show answer

After the first outer pass j is already 2, so the inner while j < 2 never runs again. The counter must be reset inside the outer loop.

6. Which tool replaces two nested loops that build every combination of two lists?

Show answer

itertools.product(list1, list2).