Sub topic 2
Counting a Single Loop
A single loop is the basic unit of running-time analysis. Every analysis later in this tutorial, including nested loops, triangular loops, and halving loops, uses the method this chapter builds: find how many times the loop runs, find how much work each pass does, and multiply.
This chapter assumes you can read and write basic Python, know how for and while loops behave, and accept the idea from the previous chapter that a step is any operation that takes constant time, such as an assignment, a comparison, or an arithmetic operation on small numbers.
The Core Model: Iterations Times Work per Iteration
An iteration is one complete pass through the loop body. For a loop whose body costs the same number of steps every time, the total cost is:
T(n) = (setup steps) + (number of iterations) × (steps per iteration)Most of the effort goes into the middle term, the number of iterations. The other two terms are usually easy to read from the code. Once you know all three, you have an exact count, and an exact count is what you later reduce to an order of growth.
The simplest case is a loop whose only job is to count its own passes:
def count_single(n):
steps = 0
for i in range(n):
steps += 1
return steps
print(count_single(10)) # 10range(n) produces the values 0, 1, ..., n-1. That is n values, so the body runs exactly n times and the function returns n. For a value of n of 1,000,000, the body runs a million times. The count depends on the input, and the cost grows in direct proportion to n.
What Happens on Each Pass
It helps to picture the loop as a small machine with four parts. The initialization runs once. The test decides whether to keep going. The body does the work. The update moves the control variable forward.
The test runs one more time than the body. The final test is the one that fails and ends the loop. This fence-post effect matters when you want an exact count, and it disappears once you move to order of growth. Python's for loop hides the test and update inside the iterator protocol, but the same structure is there: the iterator is asked for a next value n + 1 times, and the last request signals that the loop is finished.
You can see the extra test by writing a while loop that records both counts:
def count_while(n):
i = 0
iterations = 0
tests = 0
while True:
tests += 1
if not (i < n):
break
iterations += 1
i += 1
return iterations, tests
print(count_while(10)) # (10, 11)Counting the Body, Not Just the Loop
Counting iterations is half the job. Each iteration also costs some number of steps, and that number multiplies the iteration count.
def sum_of_squares(n):
total = 0 # 1 step, runs once
for i in range(n): # n iterations
sq = i * i # 2 steps: multiply, assign
total += sq # 2 steps: add, assign
return total # 1 step, runs once
print(sum_of_squares(4)) # 0 + 1 + 4 + 9 = 14Each line's cost multiplied by how often it runs gives:
| Line | Steps per run | Times run | Total |
|---|---|---|---|
| `total = 0` | 1 | 1 | 1 |
| `sq = i * i` | 2 | n | 2n |
| `total += sq` | 2 | n | 2n |
| `return total` | 1 | 1 | 1 |
So T(n) = 4n + 2. Someone else might count total += sq as one step and get 3n + 2, and if they also charge for the loop's test and update they might get 5n + 3. All of these are correct under their own counting rules. They differ only in the constant multiplying n and the constant added at the end, and both constants are dropped later when you reduce counts to Big-O. What every reasonable count agrees on is that the cost is a linear function of n.
Reading the Iteration Count from Common Loop Forms
Most single loops you meet are small variations on range(n) or a while loop that counts up by one. The table below lists the common forms and their exact iteration counts. Each one is worth checking against your intuition, because small differences in bounds cause off-by-one errors.
| Loop form | Values of the control variable | Iterations |
|---|---|---|
| `for i in range(n)` | 0, 1, ..., n−1 | n |
| `for i in range(1, n)` | 1, 2, ..., n−1 | n − 1 |
| `for i in range(n + 1)` | 0, 1, ..., n | n + 1 |
| `i = 0` / `while i < n: i += 1` | 0, 1, ..., n−1 | n |
| `i = 0` / `while i <= n: i += 1` | 0, 1, ..., n | n + 1 |
| `i = 1` / `while i <= n: i += 1` | 1, 2, ..., n | n |
| `i = n` / `while i > 0: i -= 1` | n, n−1, ..., 1 | n |
| `for x in items` | each element once | len(items) |
A reliable way to count is to list the first and last values the control variable takes inside the body, then count from first to last. For a step of 1, the count is last − first + 1. For while i <= n starting at 0, the values are 0 through n, so the count is n − 0 + 1 = n + 1. The next chapter extends this to arbitrary start values, stop values, and step sizes.
Loops over Collections
When a loop walks over a list, string, or other collection, the iteration count is the collection's length. In that case, n is the size of the input rather than a number passed in as an argument:
def count_vowels(text):
count = 0
for ch in text: # len(text) iterations
if ch in "aeiou": # constant: the vowel string has fixed length 5
count += 1
return count
print(count_vowels("loop counting")) # 5Here the loop runs len(text) times. The membership test ch in "aeiou" scans a string, but that string always has five characters, so the scan costs at most five comparisons whatever the input is. That makes it a constant-cost step. The cost would change if the string being scanned grew with the input, and a later chapter on hidden loops covers that case.
The if also means some iterations do more work than others. One where ch is a vowel performs the increment, and one where it isn't skips it. The per-iteration cost is between a fixed minimum and a fixed maximum, so the total is still between c₁·n and c₂·n for constants c₁ and c₂. The number of iterations does not change, only the work per iteration, and that work is bounded by a constant.
Gotcha: Changing the Loop Variable Inside a `for` Loop
In some languages, changing the loop variable inside a for loop changes how many times the loop runs. In Python's for loop over a range, it doesn't. Each iteration takes the next value from the iterator and overwrites whatever you assigned:
steps = 0
for i in range(5):
i += 100 # has no effect on the next iteration
steps += 1
print(steps) # 5A while loop works differently. Its test reads the current value of the variable, so every change you make inside the body counts:
i = 0
steps = 0
while i < 10:
i += 3
steps += 1
print(steps) # 4 (i takes the values 0, 3, 6, 9 inside the body)When you analyze a while loop, trace the control variable through its updates. Don't assume it moves by one each time. The update rule is what determines the count. This is also why halving loops, covered later, run far fewer times than counting loops.
Common Errors When Counting a Single Loop
- Counting tests instead of iterations. The test runs
n + 1times. The body runsntimes. Know which one you are counting. - Off-by-one in bounds.
<and<=differ by one iteration, and so dorange(n)andrange(n + 1). List the first and last values to settle it. - Treating the body as one step when it isn't. A body that calls a function, slices a list, or tests membership in a growing collection may cost more than a constant. Count the body's real cost before you multiply.
- Confusing the value of an argument with the size of the input.
for x in itemsdepends onlen(items), not on any value stored initems. - Assuming a
whilevariable moves by one. Read the update line.i += 3,i -= 1, andi *= 2all lead to different counts.
Exercise
How many times does the body of this loop run, and what is T(n) if each of the two body lines costs 1 step and the two lines outside the loop cost 1 step each? total = 0 / for i in range(1, n + 1): / x = i + 1 / total += x / return total
Show answer
The control variable takes the values 1 through n, so the body runs n times. Each iteration costs 2 steps, giving 2n, and the two lines outside the loop add 2. T(n) = 2n + 2, which is linear in n.
Exercise
For i = n followed by while i >= 0: i -= 1, how many times does the body run, and how many times is the test i >= 0 evaluated?
Show answer
Inside the body, i takes the values n, n−1, ..., 0, which is n + 1 values, so the body runs n + 1 times. The test is evaluated one more time than the body, when i is −1 and the test fails, so it runs n + 2 times.
Exercise
A function loops for word in words: and inside the body runs if word == "stop": found = True. If words has 500 elements, how many iterations run, and does the comparison make the cost per iteration non-constant?
Show answer
The loop runs 500 iterations, one per element, because nothing exits early. The comparison checks one word against a fixed string of length 4. It stops after at most a few character comparisons, so it costs at most a constant amount per iteration. The total is linear in len(words).