Python Nested Loops and Pair Generation
Core idea
A nested loop is a loop inside another loop. With a fixed nonempty inner sequence, each outer iteration runs the inner loop from the beginning. For two complete loops with m and n items, the inner body runs m × n times. Indentation determines which statements run per pair, per outer item, or after both loops.
for row in ["A", "B"]: for slot in range(1, 4): print(f"{row}{slot}")Each row receives three slots. The inner loop finishes A before the outer loop moves to B.
Reset a row count
for row in range(1, 3): count = 0 for slot in range(3): count = count + 1 print(row, count)count starts from zero for each row. The print after the inner loop runs once per row.
Break only the inner loop
for row in ["A", "B"]: for slot in range(1, 4): if slot == 2: break print(row, slot)Each inner loop stops at slot 2; the outer loop still visits both rows.
Common mistake
A total for all pairs must be initialized before both loops. Initializing it inside the outer loop loses earlier rows. A break in the inner loop does not exit the outer loop.
Practice
Mini-project: print labels for 3 rows with 2 slots each, then print the total number of labels. Try zero rows. Next chapter: lists and mutable sequences.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested loops and pair counts
Check your understanding of nested loops.
What is printed?
count = 0for row in range(2): for col in range(3): count = count + 1print(count)What is printed?
for row in range(2): count = 0 for col in range(2): count = count + 1 print(count)What is printed?
for row in "AB": for slot in range(2): if slot == 1: break print(row)If the outer sequence is empty, how many times does the inner body run?