Sub topic 5
Nested Loops: Multiplying Costs
This chapter assumes you can read Python for loops and count how many times a single loop runs from its start, stop, and step values. It also assumes you know that the costs of blocks running one after another add together. Here you learn what happens when one loop sits inside another.
The Multiplication Rule
A loop is nested when its whole body runs inside another loop's body. If the inner loop's bounds do not depend on the outer loop variable, the inner loop runs the same number of times on every outer iteration. The total work is then the outer count times the inner count.
def count_grid(n, m):
steps = 0
for i in range(n):
for j in range(m):
steps += 1
return steps
print(count_grid(4, 5)) # 20The outer loop runs 4 times. Each of those 4 iterations starts the inner loop from scratch, and the inner loop runs 5 times. The body steps += 1 therefore runs 4 × 5 = 20 times. In general it runs n · m times.
Counting From the Inside Out
For deeper nesting, work from the innermost loop outward:
- Count the cost of the innermost body. If it is a fixed set of basic operations, call it c.
- Multiply by the number of inner iterations to get the cost of one full inner loop.
- That result becomes the body cost of the next loop out. Multiply again.
Three independent loops of sizes a, b, and d with a body of cost c cost c · a · b · d. A triple loop where every bound is n costs c · n³.
The rule also covers loops with other step sizes. If the outer loop is range(0, n, 2) and the inner loop is range(m), the outer loop runs ⌈n/2⌉ times. The total is ⌈n/2⌉ · m.
import math
def count_stepped(n, m):
steps = 0
for i in range(0, n, 2):
for j in range(m):
steps += 1
return steps
n, m = 7, 3
print(count_stepped(n, m)) # 12
print(math.ceil(n / 2) * m) # 12Nested Versus Sequential
The most common mistake is mixing up nesting and sequence. Compare these two shapes:
| Shape | Structure | Body executions |
|---|---|---|
| Sequential | loop over n, then a separate loop over m | n + m |
| Nested | loop over m inside loop over n | n · m |
The indentation tells you which rule applies. A loop that starts after another loop has finished adds its cost. A loop that starts inside another loop's body multiplies its cost.
Mixed code combines both rules. Suppose the outer loop runs n times, and its body holds one constant-time statement followed by an inner loop of m iterations. One outer iteration costs 1 + m, so the total is n · (1 + m) = n + n·m.
When the Rule Stops Working
The multiplication rule needs the inner count to stay the same on every outer iteration. If the inner loop is written range(i, n) or range(i), its length changes with i, and n · m no longer describes it. Those loops need a sum over the outer variable. A later chapter covers that sum.
Two quick checks help before you multiply:
- Does the inner loop's range mention the outer variable? If it does, don't multiply.
- Can the inner loop exit early with
breakorreturn? If it can, the product is only the worst case.
Exercise
How many times does the line steps += 1 run in this code, as a formula in n and m? for i in range(n): steps += 1; for j in range(m): for k in range(0, m, 3): steps += 1 (the first steps += 1 is in the outer body, and the j/k loops are nested inside the outer loop after it).
Show answer
Each outer iteration runs 1 step plus m · ⌈m/3⌉ steps from the j and k loops. Over n outer iterations the total is n · (1 + m · ⌈m/3⌉) = n + n · m · ⌈m/3⌉.
Exercise
A function loops over 100 rows. For each row it loops over 8 columns, and for each cell it runs 2 basic operations. A colleague says the cost is 100 + 8 + 2 = 110 operations. What is wrong, and what is the correct count?
Show answer
The colleague added the costs as if the loops ran in sequence. The loops are nested, so the costs multiply: 100 · 8 · 2 = 1600 basic operations.