Sub topic 4
Stepping and counting backwards
This chapter assumes you know the one-, two-, and three-argument forms of range() and can write a basic for loop. Here you will use the third argument, step, to skip values and to count down.
The step argument
The full form is range(start, stop, step). The loop begins at start and adds step after each iteration. It stops as soon as the next value would reach or pass stop. The stop value is never produced.
for n in range(0, 10, 3):
print(n) # 0, 3, 6, 9The default step is 1. You cannot give step without also giving start and stop, because range has no keyword arguments.
Counting backwards
A negative step makes the sequence go down. Then start must be larger than stop, and stop is still excluded.
for n in range(5, 0, -1):
print(n) # 5, 4, 3, 2, 1
for n in range(10, 0, -3):
print(n) # 10, 7, 4, 1The first loop never prints 0, because 0 is the excluded stop value. To include 0, set the stop to -1:
print(list(range(5, -1, -1))) # [5, 4, 3, 2, 1, 0]How range decides when to stop
The direction of the step decides which comparison range makes against stop.
Common errors
| Call | Result |
|---|---|
| `range(0, 5, -1)` | Empty. The step points away from `stop`. |
| `range(5, 0)` | Empty. The default step is `+1`. |
| `range(1, 10, 0)` | `ValueError`, because the step cannot be zero. |
| `range(0, 1, 0.5)` | `TypeError`, because all arguments must be integers. |
An empty range does not raise an error. The loop body simply never runs, which can hide a wrong-direction bug.
Reversing with reversed()
When you only want to walk an existing range backwards, reversed() often reads better than working out the negative bounds yourself:
for n in reversed(range(1, 6)):
print(n) # 5, 4, 3, 2, 1Both forms give the same values. reversed(range(1, 6)) states the intent directly, while range(5, 0, -1) makes you compute the start and stop yourself.
You often need reverse order for index work, such as visiting a list from the last position to the first:
items = ["a", "b", "c"]
for i in range(len(items) - 1, -1, -1):
print(i, items[i]) # 2 c, 1 b, 0 aHere len(items) - 1 is the last valid index, and -1 as the stop makes sure index 0 is included. If you only need the values, for item in reversed(items) is simpler.
Exercise
What does list(range(20, 0, -5)) produce, and why does it not include 0?
Show answer
It produces [20, 15, 10, 5]. The sequence stops before reaching the stop value 0, because stop is always excluded. It also would not land on 0 here, since 5 minus 5 equals 0, which is excluded.
Exercise
Write a range call that produces 10, 8, 6, 4, 2, 0.
Show answer
range(10, -1, -2). The stop is -1 so that 0 is included, and the step -2 skips every other number.