Sub topic 11
Nested loops
This chapter assumes you can write a basic for loop over a list or range(), and that you know how indentation marks a block. A nested loop is a loop placed inside the body of another loop.
How nesting executes
The inner loop runs from start to finish on every iteration of the outer loop. If the outer loop runs 3 times and the inner loop runs 4 times, the inner body runs 3 × 4 = 12 times.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()The output is a 3 by 3 multiplication table:
1 2 3
2 4 6
3 6 9 The end=" " argument keeps each row on one line. The bare print() sits in the outer loop's body, so it runs once per row and starts a new line.
Inner bounds can depend on the outer variable
The inner iterable is evaluated again on each outer iteration, so it can use the outer loop variable. This is how you visit each pair of items once, without repeats or self-pairs.
letters = ["a", "b", "c"]
for i in range(len(letters)):
for j in range(i + 1, len(letters)):
print(letters[i], letters[j])This prints a b, a c and b c.
break only leaves one loop
A break ends the innermost loop that contains it. The outer loop keeps going. This is the most common surprise with nested loops.
nums = [3, 8, 5, 1]
target = 13
found = None
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
found = (nums[i], nums[j])
break
if found is not None:
break
print(found) # (8, 5)The inner break stops the search for a partner. The second break, guarded by a flag check, stops the outer loop. Two other approaches also work:
- Put the loops in a function and use
returnto leave both at once. - Use the loop
elseclause, which runs only if the inner loop did notbreak.
def find_pair(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return nums[i], nums[j]
return None
print(find_pair([3, 8, 5, 1], 13)) # (8, 5)A function is usually the clearest option, because the name documents what the search does.
Common errors
- Reusing a variable name. If both loops use
i, the inner loop overwrites the outer variable. The outer loop still advances correctly on its next iteration, but any code after the inner loop sees the wrong value. - Wrong indentation. A statement indented under the inner loop runs once per inner iteration. The same statement indented under the outer loop runs once per outer iteration. The
print()in the first example shows the difference. - Hidden cost. Work grows with the product of the loop sizes. Two nested loops over 1,000 items each run 1,000,000 times. Three levels over the same data run a billion times.
When to flatten
If you need every combination of two iterables, itertools.product replaces the two loops with one:
from itertools import product
for color, size in product(["red", "blue"], ["S", "M"]):
print(color, size)Use explicit nesting when the inner bounds depend on the outer variable, or when you need work between the loops. Use product when you simply want all combinations.
Exercise
This code runs print("x") inside two nested loops: the outer is for a in range(4) and the inner is for b in range(3). How many times does it print? What changes if you add break directly after the print in the inner loop?
Show answer
It prints 4 × 3 = 12 times. With break after the print, the inner loop stops after its first iteration on each pass, so the output is 4 lines. The outer loop still runs all 4 times, because break ends only the inner loop.