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 defines a block. You will learn how a loop inside a loop executes, how to count its iterations, and how break, continue and else behave when loops are nested. You will also see the mistakes that nesting tends to produce.
What a nested loop is
A nested loop is a loop whose body contains another loop. The inner loop runs from start to finish every time the outer loop runs its body once.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()This prints a 3 by 3 multiplication table:
1 2 3
2 4 6
3 6 9 The inner print(i * j, end=" ") keeps the output on one line. The bare print() after the inner loop ends the line. It is indented at the outer loop's level, so it runs once per row.
The order of execution is the important part. The outer variable changes slowly and the inner variable changes quickly, like the hours and minutes on a clock.
for i in range(2):
for j in range(3):
print(i, j)The output is 0 0, 0 1, 0 2, 1 0, 1 1, 1 2, one pair per line. The inner loop finishes all three of its iterations before i moves from 0 to 1.
Counting iterations
If the inner loop's size does not depend on the outer variable, the body runs outer_size * inner_size times. The table above runs its body 3 * 3 = 9 times.
This matters for performance. Comparing every pair in two lists of 1,000 items runs the body 1,000,000 times. Adding a third level multiplies by another factor. When code feels slow, check how deeply its loops are nested before you look elsewhere.
Inner ranges that depend on the outer variable
The inner loop can use the outer loop variable in its bounds. Each outer iteration then gets a different amount of inner work.
for row in range(1, 5):
for col in range(row):
print("*", end="")
print()*
**
***
****On the first pass range(1) produces one value. On the last pass range(4) produces four. The total body count is 1 + 2 + 3 + 4 = 10, not 4 * 4. When you predict iteration counts, add up the inner sizes instead of multiplying.
A common use of this pattern is comparing each pair of items once. Starting the inner range after the outer index skips duplicates and self-comparisons:
items = ["a", "b", "c", "d"]
for i in range(len(items)):
for j in range(i + 1, len(items)):
print(items[i], items[j])This prints the six unordered pairs: a b, a c, a d, b c, b d, c d.
Looping over nested data
Nested loops are the natural way to visit a list of lists. Name the variables after what they hold, not i and j, so the code explains itself.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0
for row in grid:
for value in row:
total += value
print(total) # 45The outer loop receives each inner list. The inner loop receives each number in that list. The same shape works for a dictionary whose values are lists, or a list of strings where you loop over characters.
When you need positions as well, use enumerate() at each level instead of range(len(...)):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value % 2 == 0:
print(f"even {value} at row {r}, column {c}")Building a grid correctly
To create a grid of zeros, use a comprehension that makes a new inner list per row:
good = [[0] * 3 for _ in range(3)]
bad = [[0] * 3] * 3
good[0][0] = 1
bad[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
print(bad) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]The multiplication * 3 in bad copies a reference to one list three times, so all three rows are the same object. Writing to one row appears to write to all of them.
break and continue in nested loops
break and continue apply only to the innermost loop that contains them. This is the most common source of confusion with nesting.
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)The output is 0 0, 1 0, 2 0. Each break stops the inner loop only. The outer loop carries on and starts the next inner loop from scratch.
continue works the same way. It skips to the next iteration of the inner loop, not the outer one.
Leaving both loops at once
Python has no break 2 statement. You have three common options.
| Technique | How it works | Best when |
|---|---|---|
| Move the loops into a function and `return` | `return` leaves every loop at once | The search is a natural unit of work |
| Flag variable | Set a flag, `break` the inner loop, test the flag in the outer loop | The code must keep running in the same scope |
| Loop `else` with `continue` | `else` on the inner loop runs only if it did not `break`, so `continue` skips the outer `break` | You want a compact, self-contained form |
The function version is usually the clearest:
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return (r, c)
return None
print(find([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 6)) # (1, 2)
print(find([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 10)) # NoneThe flag version keeps everything in one scope:
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 6
found = None
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
found = (r, c)
break
if found is not None:
break
print(found) # (1, 2)The else version replaces the flag test:
found = None
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
found = (r, c)
break
else:
continue
breakRead it as: if the inner loop finished without break, continue the outer loop. Otherwise fall through to the outer break. It is correct but easy to misread, so prefer a function when you can.
Loop else with nesting
The else clause of a loop runs when the loop ends without hitting break. In a nested loop it attaches to whichever loop it is indented with. The prime-number example shows the inner form:
for n in range(2, 10):
for d in range(2, n):
if n % d == 0:
break
else:
print(n, "is prime")The else lines up with the inner for, so it asks one question per n: did the divisor search finish without finding a factor? It prints 2, 3, 5 and 7. Note that for n = 2 the inner range is empty, so the loop ends immediately and the else runs.
Common mistakes
- Reusing a variable name. If the inner loop uses the same name as the outer one, it overwrites the outer variable. The outer loop still advances correctly, because it takes its next value from its own iterator. But any use of the variable after the inner loop sees the wrong value. Use distinct names.
- Wrong indentation of the closing statement. In the multiplication table, indenting
print()one level deeper puts it inside the inner loop, and you get a blank line after every number instead of every row. - Assuming
breakstops everything. It stops only the innermost loop, as shown above. - Hidden quadratic cost. A
forloop containingx in some_listis a nested loop, because the membership test scans the list. Converting the list to a set removes the inner scan.
Flattening with itertools.product
When the inner loops are independent of each other and you do not need code between them, itertools.product produces the same pairs with a single loop:
from itertools import product
for i, j in product(range(2), range(3)):
print(i, j)This prints the same six pairs as the earlier nested version, in the same order. It also changes how break behaves: there is only one loop, so break leaves the whole iteration. It cannot express dependent bounds such as range(i + 1, n), and it cannot run code between the inner loop and the next outer item.
Exercise
How many times does print() run in this code, and what is the last line printed? for i in range(4): for j in range(i): print(i, j)
Show answer
It runs 6 times. For i = 0 the inner range is empty, then i = 1, 2 and 3 give 1, 2 and 3 inner iterations, and 1 + 2 + 3 = 6. The last line printed is "3 2".
Exercise
In the code below, the outer loop has three iterations. What does it print? for i in range(3): for j in range(3): if j == i: break print(i, j)
Show answer
It prints "1 0", "2 0" and "2 1". The break leaves only the inner loop. For i = 0 it fires on the first inner iteration, so nothing prints. For i = 1 it prints j = 0 and breaks at j = 1. For i = 2 it prints j = 0 and j = 1 and breaks at j = 2.