Sub topic 2
Counting a Single Loop
This chapter assumes you can read Python for and while loops and that you know the idea from the previous chapter: a step is one constant-time basic operation, such as an assignment, a comparison, or an addition. Here we apply that idea to the simplest structure that makes running time grow with input size, which is a single loop.
The working model
A single loop's cost comes down to one formula:
total steps = (number of iterations) × (steps per iteration) + (steps outside the loop)
The work outside the loop, such as setting up a variable or returning a result, happens once. The body happens once per iteration. When the input gets large, the iteration count is what grows, so most of your effort goes into getting that number right.
Counting `range(n)`
A loop over range(n) visits the values 0, 1, ..., n − 1. That is exactly n values, so the body runs n times.
def count_single(n):
steps = 0
for i in range(n):
steps += 1
return steps
print(count_single(10)) # 10The counter steps goes up once per iteration, so it returns n. This is the cleanest way to see what "the loop runs n times" means. A later chapter turns this trick into a general way to check your predictions.
Where the steps go
The table below charges each part of count_single with its cost. Each line counts as one step, and we ignore how long Python takes to run each line.
| Part of the code | Times executed | Steps |
|---|---|---|
| `steps = 0` | 1 | 1 |
| loop advances to the next `i` | n | n |
| `steps += 1` | n | n |
| `return steps` | 1 | 1 |
| **Total** | 2n + 2 |
The exact total depends on how finely you count. Someone else might charge 3 steps for the loop machinery and get 4n + 2. Either way the total has the form a·n + b, where a and b are constants. That shape is what matters, and a later chapter explains why the constants get dropped.
The same loop written with `while`
A while loop makes the moving parts visible: an initialization, a test, a body, and an update.
def count_while(n):
steps = 0
i = 0
while i < n:
steps += 1
i += 1
return steps
print(count_while(10)) # 10The test i < n is evaluated n + 1 times. It passes n times and fails once, which ends the loop. The body and the update each run n times.
Common errors
- Off-by-one counts.
range(1, n + 1)runs n times, andrange(1, n)runs n − 1 times. A quick check is to list the values for a tiny n, such as n = 3, and count them. - Forgetting the body's cost. If the body contains 4 constant-time operations, the loop costs 4n, not n. The growth stays linear, but the exact count changes.
- Treating a body as constant when it isn't. A call such as
sum(items)orx in some_listinside the body hides its own loop. Later chapters handle that case. For now, count only bodies that are truly constant time. - Mixing up the test and the body. The test runs one more time than the body. That matters for exact counts but not for order of growth.
Exercise
How many times does the body of for i in range(2, n + 2): total += i * i run? Assuming the body is 2 steps and the setup and return outside the loop are 2 steps in total, give the exact step count, ignoring the loop's own advancing steps.
Show answer
range(2, n + 2) covers 2, 3, ..., n + 1, which is (n + 2) − 2 = n values, so the body runs n times. The total is 2n + 2 steps.
Exercise
In count_while(5), how many times is the condition i < n evaluated, and how many times does i += 1 run?
Show answer
The condition is evaluated 6 times: it is true for i = 0 through 4 and false once at i = 5. The update i += 1 runs 5 times.