Sub topic 3
Start, Stop, and Step: Exact Iteration Counts
The previous chapter counted loops of the form for i in range(n), which run exactly n times. Real loops rarely look that clean. They start at 1 instead of 0, stop at n - 1 or include n, skip by twos or fives, or count downward. This chapter turns any arithmetic loop (one whose control variable changes by a fixed amount each time) into an exact iteration count.
This chapter assumes you can read Python for and while loops, know how range behaves at the edges, and are comfortable with basic algebra, including the ceiling function. The ceiling of x, written ⌈x⌉, is the smallest integer greater than or equal to x.
Why Exact Counts Matter Here
Later chapters drop constants and keep only the order of growth. You might ask why you should count exactly now. Exact counts are the input to everything that follows. When a nested loop's inner bound is n - i - 1, an off-by-one error in the inner count turns into a wrong summation, and a wrong summation can hide a mistake in the leading term. Counting exactly also lets you check your reasoning against a running program, because len(range(...)) and an instrumented counter give exact numbers too.
The Core Formula for `range(a, b, s)`
A range(a, b, s) produces the values a, a + s, a + 2s, and so on, and stops before reaching or passing b. The stop value b is always excluded.
For a positive step s and b > a, the k-th value (counting from 0) is a + k*s. The loop runs while a + k*s < b, which means k < (b - a) / s. The number of valid values of k is the number of non-negative integers below (b - a) / s, which is:
count = ⌈(b − a) / s⌉
If b <= a, the range is empty and the count is 0. The full rule for positive steps is therefore:
count = max(0, ⌈(b − a) / s⌉)
Here is a check with a = 3, b = 20, s = 4. The values are 3, 7, 11, 15, 19, so there are five of them. The formula gives ⌈17 / 4⌉ = ⌈4.25⌉ = 5.
import math
a, b, s = 3, 20, 4
print(list(range(a, b, s))) # [3, 7, 11, 15, 19]
print(len(range(a, b, s))) # 5
print(math.ceil((b - a) / s)) # 5Why the ceiling and not the floor
The ceiling matters whenever b - a is not a multiple of s. With range(0, 10, 3) the values are 0, 3, 6, 9. That is four values. The ratio 10/3 is 3.33, and the floor would give 3, which misses the last value. The partial step at the end still has a starting point inside the range, so it counts as an iteration.
When b - a is an exact multiple of s, the ceiling and the floor agree. range(0, 12, 3) gives 0, 3, 6, 9, which is 12/3 = 4 values, and 12 is excluded.
Negative Steps
A negative step counts downward, and the loop runs while the value stays strictly greater than b. The same formula works unchanged if you keep the signs:
count = max(0, ⌈(b − a) / s⌉)
For range(10, 0, -3) the values are 10, 7, 4, 1. The formula gives ⌈(0 − 10) / (−3)⌉ = ⌈3.33⌉ = 4. Both the numerator and the denominator are negative, so the ratio is positive whenever the range moves in the direction of its step.
If the direction is wrong, as in range(0, 10, -1), the ratio is negative and max clamps the count to 0. Python agrees: that range is empty. A step of 0 raises ValueError, and the formula would divide by zero, so the two fail in the same place.
Computing the Count with Integers Only
math.ceil((b - a) / s) uses floating-point division. For very large integers, around 2^53 and above, the float can round and the ceiling comes out off by one. Python's floor division // always rounds toward negative infinity, and that gives an exact integer ceiling:
⌈x / y⌉ = −((−x) // y)
Rearranged for our case, this becomes -((a - b) // s), and it works for both positive and negative steps.
import random
def iteration_count(a, b, s):
"""Number of values produced by range(a, b, s), using integer math only."""
if s == 0:
raise ValueError("step must not be zero")
return max(0, -((a - b) // s))
# Compare against Python's own range on many random cases.
random.seed(1)
for _ in range(100_000):
a = random.randint(-50, 50)
b = random.randint(-50, 50)
s = random.choice([x for x in range(-7, 8) if x != 0])
assert iteration_count(a, b, s) == len(range(a, b, s)), (a, b, s)
print(iteration_count(3, 20, 4)) # 5
print(iteration_count(10, 0, -3)) # 4
print(iteration_count(5, 2, 1)) # 0
print(iteration_count(0, 10**20, 7) == len(range(0, 10**20, 7))) # Truelen(range(...)) takes constant time in Python. It computes the same formula and does not build the list. That makes it a free oracle for checking your hand counts on any for loop over a range.
Inclusive Bounds and the Fencepost Problem
Pseudocode and math texts often write "for i from a to b", which includes both ends. In Python that is range(a, b + 1), and the count is:
count = b − a + 1 (for a ≤ b)
This is the fencepost problem. A fence 10 metres long with a post every metre has 11 posts, not 10. People who subtract the endpoints and forget the +1 undercount by one. People who add 1 to an exclusive range overcount by one.
With a step, an inclusive loop from a to b runs ⌊(b − a) / s⌋ + 1 times for positive s and a ≤ b. Here is a check: from 0 to 10 inclusive by 3 gives 0, 3, 6, 9, which is ⌊10/3⌋ + 1 = 4 values. Another way to get the same answer is to convert to an exclusive bound, range(a, b + 1, s), and apply the main formula: ⌈11/3⌉ = 4. Both routes agree, so pick whichever one you are less likely to get wrong.
The table below collects the common shapes. n is assumed to be at least 1.
| Loop | Values | Iterations |
|---|---|---|
| `range(n)` | 0 … n−1 | n |
| `range(1, n)` | 1 … n−1 | n − 1 |
| `range(1, n + 1)` | 1 … n | n |
| `range(i, n)` | i … n−1 | n − i (0 if i ≥ n) |
| `range(i + 1, n)` | i+1 … n−1 | n − i − 1 (0 if i ≥ n−1) |
| `range(0, n, 2)` | 0, 2, 4, … | ⌈n / 2⌉ |
| `range(1, n, 2)` | 1, 3, 5, … | ⌊n / 2⌋ |
| `range(n - 1, -1, -1)` | n−1 … 0 | n |
| `range(0, n, k)` | 0, k, 2k, … | ⌈n / k⌉ |
The rows range(i, n) and range(i + 1, n) come back in the chapter on triangular loops. There, i is an outer loop variable and these counts become the terms of a sum.
While Loops with Arithmetic Updates
A while loop has no range to call len on, but it is often a range in disguise. This loop:
i = a
while i < b:
# body
i += sruns exactly as many times as range(a, b, s) for positive s. If you change < to <=, it becomes inclusive and matches range(a, b + 1, s) for integers. If you change the update to i -= s with the condition i > b, it matches range(a, b, -s).
To count any such loop, rewrite it as a range and use the formula. Four things must hold for that translation to be valid:
- The control variable starts at a known value.
- It changes by the same fixed amount on every iteration.
- Nothing else in the body modifies it.
- The condition compares it against a bound that does not change during the loop.
If any of these fails, the loop is not arithmetic. A loop that multiplies or halves its variable is the subject of a later chapter. A loop whose body sometimes changes i needs case analysis.
Gotchas
`for` evaluates `range` once; `while` re-evaluates its condition
A for loop builds its range object before the first iteration. Changing the bound variable inside the body has no effect on the count:
n = 5
count = 0
for i in range(n):
n = 100 # rebinding n does not change the existing range(5)
count += 1
print(count) # 5A while loop re-checks its condition every time, so the same change does affect it:
n = 5
i = 0
count = 0
while i < n:
n = 8 # the condition now sees the new bound
i += 1
count += 1
print(count) # 8When you count a while loop, confirm that its bound really stays fixed.
Assigning to the loop variable inside a `for` body
In Python, for i in range(n): i += 2 does not skip iterations. The next pass takes the next value from the range and overwrites i. In C, Java, or JavaScript, a classic for (i = 0; i < n; i++) loop does respect changes to i inside the body. A translated algorithm can therefore run a different number of times in Python than in the original language.
Floating-point steps
Loops that use float steps, such as x = 0.0; while x < 1.0: x += 0.1, are fragile to count. Ten additions of 0.1 give 0.9999999999999999, which is still less than 1.0, so this loop runs 11 times instead of 10. When the count matters, loop over integers and compute the float from them: x = k / 10.
Empty ranges are not errors
range(5, 2) is empty, and so is range(i + 1, n) when i = n - 1. These silent zeros are correct, and they matter: in nested loops, the last few outer iterations often contribute zero inner iterations. Your formula needs the max(0, …) clamp, or the sums you build from it will include negative terms.
Exercises
Exercise
How many times does for i in range(7, 50, 6) run? List the values to confirm.
Show answer
⌈(50 − 7) / 6⌉ = ⌈43 / 6⌉ = ⌈7.17⌉ = 8. The values are 7, 13, 19, 25, 31, 37, 43, 49. The next value, 55, is not below 50, so the loop stops after 8 iterations.
Exercise
How many times does for i in range(100, 3, -7) run?
Show answer
⌈(3 − 100) / (−7)⌉ = ⌈97 / 7⌉ = ⌈13.86⌉ = 14. The last value is 100 − 13·7 = 9, which is still greater than 3. The next value, 2, is not, so the loop runs 14 times. You can confirm with len(range(100, 3, -7)).
Exercise
The loop i = 2; while i <= n: i += 3 runs for some integer n ≥ 2. Give an exact formula for the number of iterations in terms of n, and check it for n = 11.
Show answer
The condition i <= n makes the loop match range(2, n + 1, 3). The count is ⌈(n + 1 − 2) / 3⌉ = ⌈(n − 1) / 3⌉, which equals ⌊(n − 2) / 3⌋ + 1. For n = 11, the values are 2, 5, 8, 11, which is 4 iterations, and ⌈10 / 3⌉ = 4.
Exercise
A colleague writes count = (b - a) // s to predict the length of range(a, b, s) for positive s. For which inputs is this wrong, and by how much?
Show answer
It is wrong whenever b − a is positive but not a multiple of s. In those cases it undercounts by exactly 1, because floor drops the final partial step, whose starting value is still inside the range. It is also wrong when b < a: it returns a negative number instead of 0. A correct version is max(0, -((a - b) // s)).