Sub topic 4
Stepping and counting backwards
This chapter covers the third argument of range(), the step. It also covers how a negative step reverses direction and which bounds you need when you count down. It assumes you already know range(stop) and range(start, stop), that the stop value is excluded, and how a basic for loop runs.
The step argument
The full form is range(start, stop, step). The step is the amount added to the current value after each iteration. The default step is 1.
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(1, 10, 3))) # [1, 4, 7]
print(list(range(1, 20, 2))) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(list(range(0, 10, 4))) # [0, 4, 8]The last line shows that the step does not have to land exactly on stop. Python produces start, start + step, start + 2*step and so on, and stops before the first value that reaches or passes stop. Here 12 would be next, and it is past 10.
You cannot pass only a step. Because arguments are positional, range(5, 2) means start 5, stop 2. If you want a step, you must also give the start, even when it is 0.
Counting backwards
A negative step makes the sequence descend. The rules mirror the ascending case:
startmust be greater thanstop, or the range is empty.stopis still excluded, so a descending range never includes it.
for n in range(5, 0, -1):
print(n)
print("liftoff")This prints 5, 4, 3, 2, 1 and then liftoff. The value 0 is missing because it is the excluded stop. To include 0, set the stop one step past it:
print(list(range(5, -1, -1))) # [5, 4, 3, 2, 1, 0]
print(list(range(10, -1, -2))) # [10, 8, 6, 4, 2, 0]For a step of -1, "one past the last wanted value" means stop = last - 1. For a step of -2 and a wanted last value of 0, a stop of -1 works because it lies beyond 0 in the descending direction.
The direction must match the step sign
Python does not guess which way you meant to count. If the sign of the step disagrees with the order of start and stop, you get an empty range, not an error.
print(list(range(0, 5, -1))) # []
print(list(range(5, 0))) # []
print(list(range(5, 0, 1))) # []A loop over an empty range runs zero times and raises no exception. That makes this a silent bug. A countdown that never runs is easy to miss, so check the direction first when a loop body seems to be skipped.
The table summarizes the cases.
| Call | Values produced | Note |
|---|---|---|
| `range(0, 10, 2)` | 0, 2, 4, 6, 8 | Ascending, 10 excluded |
| `range(10, 0, -2)` | 10, 8, 6, 4, 2 | Descending, 0 excluded |
| `range(10, -1, -2)` | 10, 8, 6, 4, 2, 0 | Stop moved past 0 |
| `range(0, 10, -1)` | none | Sign of step disagrees with direction |
| `range(10, 0)` | none | Default step is +1 |
Invalid steps
Two step values are rejected outright.
try:
range(0, 10, 0)
except ValueError as e:
print(e) # range() arg 3 must not be zero
try:
range(0, 1, 0.1)
except TypeError as e:
print(e) # 'float' object cannot be interpreted as an integerA zero step would never move, so Python raises ValueError when the range is created, before any loop runs. A float step raises TypeError because range accepts only integers (or objects that implement __index__).
If you need fractional steps, loop over integers and scale them. This avoids accumulating floating-point error from repeated addition.
for i in range(5):
print(i * 0.25) # 0.0, 0.25, 0.5, 0.75, 1.0Predicting the length
You can compute how many values a range yields without iterating. For a non-zero step, the length is the ceiling of (stop - start) / step, or 0 if that is negative.
import math
def expected_len(start, stop, step):
return max(0, math.ceil((stop - start) / step))
for args in [(0, 10, 3), (10, 0, -3), (0, 5, -1), (5, -1, -1)]:
print(args, len(range(*args)), expected_len(*args))The two lengths match on every line: 4, 4, 0 and 6. You rarely need this formula in practice, because len() works on a range directly. It is useful when you reason about off-by-one problems. A range with n values and step s ends at start + (n - 1) * s, and r[-1] gives that last value.
r = range(10, 0, -3)
print(list(r)) # [10, 7, 4, 1]
print(len(r)) # 4
print(r[-1]) # 1Negative step or reversed()?
There are two ways to walk a sequence of integers backwards. Both give the same values.
for n in range(5, 0, -1):
print(n, end=" ")
print()
for n in reversed(range(1, 6)):
print(n, end=" ")
print()Both lines print 5 4 3 2 1. The reversed(range(1, 6)) form states the ascending bounds you already understand and flips the order, so it is often easier to read and avoids the stop-is-excluded arithmetic. Slicing agrees as well: range(1, 6)[::-1] is range(5, 0, -1). The negative-step form is more direct when the step is not 1, as in range(100, 0, -10).
Counting backwards over list indexes
A common reason to descend is to visit a list from the end. The last valid index is len(items) - 1, and the stop must be -1 so that index 0 is included.
items = ["a", "b", "c", "d"]
for i in range(len(items) - 1, -1, -1):
print(i, items[i])This prints indexes 3, 2, 1, 0. Here -1 appears twice with different meanings: the stop is the integer -1 (one past 0), and the step is -1. Do not confuse the stop with the negative index items[-1]. The range only produces integers, and you apply them to the list yourself.
Descending order also makes it safe to delete items by index. Removing the item at index i only shifts items after i, and you have already visited those.
nums = [3, -1, 4, -1, 5]
for i in range(len(nums) - 1, -1, -1):
if nums[i] < 0:
del nums[i]
print(nums) # [3, 4, 5]The range is computed once, from the original length, and each deletion only affects positions you have already passed. Going forwards with the same code would skip elements or raise IndexError. When you can, building a new list is still the clearer choice.
Checklist for choosing bounds
- Decide the first and last values you want.
- Pick the step and its sign from the direction of travel.
- Set
startto the first value. - Set
stopto the last value plus one for a positive step, or minus one for a step of -1. For larger steps, any value past the last wanted value and not past the next one works. - Test with
list(range(...))on a small case before using it in a loop.
Exercise
Write a loop with range() that prints 20, 15, 10, 5, 0, in that order, one per line. Then say what range(20, 0, -5) produces and why.
Show answer
for n in range(20, -1, -5): print(n). The stop of -1 lies past 0, so 0 is included. range(20, 0, -5) produces 20, 15, 10, 5 because the stop value 0 is excluded.
Exercise
What do list(range(3, 8, -1)) and range(0, 4, 0) do?
Show answer
list(range(3, 8, -1)) gives [] because the step is negative but start is below stop, so no value qualifies. range(0, 4, 0) raises ValueError when the range is created, because the step must not be zero.