runtime
25 / 250
lesson 25 Loops & Iteration · beginner

A loop inside a loop

For each pass of the outer loop, the inner loop runs all the way through. That gives you grids, combinations and every pair.

You'll be able to
  • Indent a second loop under the first and see it restart on every outer pass
  • Build one line of a grid per outer pass
  • Compare every character with every other one
The idea

Some results have two directions: rows and seats in a cinema, sizes and colours of a T-shirt. Put one for inside another. For each pass of the outer loop, the inner loop starts again from its beginning and runs all the way through. 3 rows with 4 seats each means the inner body runs 3 × 4 = 12 times.

Indentation shows which loop a line belongs to. A line under the inner for runs for every seat. A line under the outer for, after the inner loop, runs once per row: the place to finish a row.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · A seat map
for row in "ABC":
    for seat in range(1, 5):
        print(row + str(seat), end=" ")
    print()
example-2.py · Every size with every colour
variants = 0
for size in "SML":
    for colour in "RB":
        print("TEE-" + size + "-" + colour)
        variants += 1
print(variants, "variants")

When to use it: grids, every combination of two things, or comparing every character with every other one.

Mistakes to avoid:

  • A value that should carry over between rows (a running count) must be set before the outer loop. Set it inside the outer loop and it restarts for every row.
  • break inside the inner loop only leaves the inner loop. The outer loop carries on with its next pass.
  • The work grows fast: 1,000 × 1,000 is a million passes.
Review
  • The inner loop restarts and runs completely on every pass of the outer loop.
  • Indentation decides whether a line runs per inner pass, per outer pass, or once at the end.
  • break only leaves the loop it is in. Next module: strings and text, with indexes, slices and methods.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

A loop inside a loop — Loops & Iteration · Runtime