Sub topic 3
Counting with range(): start, stop, step
This chapter assumes you can write and run a Python 3 script. It also assumes you know variables, indentation, print(), integers, and the basic for statement. By the end you will be able to predict exactly which numbers range() produces for any call. You will also be able to recognize the errors that bad arguments cause.
Why range() exists
A for loop walks over an iterable. Sometimes you have no collection to walk over. You just want "do this 10 times" or "visit every third number from 0 to 99". range() builds that sequence of integers for you.
for i in range(5):
print(i)This prints 0, 1, 2, 3 and 4, each on its own line. The loop runs five times, and i takes each value in turn.
The three forms
range() accepts one, two, or three integer arguments. The meaning of each argument depends on how many you pass.
| Call | start | stop | step | Values produced |
|---|---|---|---|---|
| `range(5)` | 0 | 5 | 1 | 0, 1, 2, 3, 4 |
| `range(2, 8)` | 2 | 8 | 1 | 2, 3, 4, 5, 6, 7 |
| `range(0, 10, 3)` | 0 | 10 | 3 | 0, 3, 6, 9 |
The defaults are start=0 and step=1. With a single argument, that argument is stop, not start. This is a quirk of the signature. You cannot write range(start=2, stop=8), because range() does not accept keyword arguments. It raises a TypeError.
The stop value is excluded
range produces numbers from start up to, but not including, stop. Mathematicians call this a half-open interval, written [start, stop).
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 3))) # [0, 3, 6, 9]
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]We wrap each call in list() here only to see the values. In a real loop you rarely need that.
The half-open design has practical benefits:
range(n)produces exactlynvalues, so "repeat n times" reads naturally.range(a, b)produces exactlyb - avalues.- Adjacent ranges join with no overlap and no gap.
range(0, 5)followed byrange(5, 10)covers 0 to 9 once each. range(len(items))yields every valid index of a sequence and nothing past its end.
How step works
The sequence is start, start + step, start + 2*step, and so on. It stops before the first value that reaches or passes stop. The final value does not have to be close to stop.
for n in range(1, 20, 6):
print(n)This prints 1, 7 and 13. The next value would be 19, which is below 20, so it is also included. Run it and check: 1, 7, 13, 19. The sequence ends because 25 would pass the limit.
A positive step counts upward, so start must be below stop for any values to appear. A negative step counts downward, so start must be above stop. The next chapter covers counting backwards in detail. For now, note that range(5, 0, -1) is how you count down from 5 to 1.
Empty ranges
If the arguments describe a sequence that cannot move from start toward stop, the range is empty. Python does not raise an error. The loop body simply never runs.
print(list(range(5, 2))) # [] start is already past stop
print(list(range(0))) # [] zero repetitions
print(list(range(3, 3))) # [] start equals stop
print(list(range(0, 5, -1))) # [] step points away from stopSilent emptiness is convenient when n can be zero, because the loop does nothing. It also hides bugs when you swap start and stop by accident. If a loop mysteriously does not run, print the range's values first.
Predicting the length
For a positive step, the number of values is max(0, (stop - start + step - 1) // step). You rarely compute this by hand, because len() does it for you.
print(len(range(0, 10, 3))) # 4: the values 0, 3, 6, 9
print(len(range(1, 101))) # 100
print(len(range(10, 0))) # 0When you are unsure about an off-by-one, check len(range(...)) against the number of iterations you want.
Arguments must be integers
range() works only with integers. Passing a float fails immediately, even when the float has no fractional part.
try:
range(0, 1, 0.1)
except TypeError as err:
print(err) # 'float' object cannot be interpreted as an integer
try:
range(5.0)
except TypeError as err:
print(err) # 'float' object cannot be interpreted as an integerIf you need fractional steps, loop over integers and scale them. This avoids the rounding drift of repeatedly adding 0.1.
for i in range(0, 10):
x = i / 10
print(x)Values that are integers but not of type int work if they implement __index__. This covers bool and NumPy integers. It does not cover floats. If n came from input() or from a division, convert it with int(...) or use // first.
n = int(input("How many? "))
for i in range(n):
print("hello", i)A step of zero is an error
A step of 0 would never advance, so Python rejects it up front.
try:
range(0, 10, 0)
except ValueError as err:
print(err) # range() arg 3 must not be zeroThis usually shows up when the step is computed, for example step = (stop - start) // count with a count larger than the distance. Guard the computation, or confirm the step is not zero before calling range().
Common idioms
Repeat an action when you do not need the counter. Using _ signals that the variable is unused.
for _ in range(3):
print("ping")Visit every other item by index:
for i in range(0, 10, 2):
print(i, end=" ") # 0 2 4 6 8
print()Build a list of squares:
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares) # [1, 4, 9, 16, 25]Every call above passes values to range() that stay fixed for the whole loop. range() reads its arguments once, when the call runs. Changing n inside the loop does not change the iterations already planned.
n = 3
for i in range(n):
n = 10 # has no effect on how many times the loop runs
print(i) # still prints 0, 1, 2Troubleshooting checklist
Work through these when a range() loop misbehaves:
- Count the values. Use
list(range(...))orlen(range(...))and compare with what you expected. - Check that
stopis exclusive. Loops that stop one early usually needstop + 1. - Check the direction. A positive step with
start >= stopis empty. - Check types. Convert floats and strings to
intbefore the call. - Check that the step is not zero.
Exercise
What does list(range(3, 15, 4)) produce, and what is len(range(3, 15, 4))? Then write a range call that produces 10, 20, 30, 40, 50.
Show answer
list(range(3, 15, 4)) is [3, 7, 11], because the next value, 15, equals stop and is excluded. So len(range(3, 15, 4)) is 3. One answer for the second part is range(10, 51, 10). The stop of 51 (or any value from 41 to 60 with step 10... use 51) ensures 50 is included while 60 is not.
Exercise
A learner writes for i in range(10, 0): print(i) expecting a countdown from 10 to 1, but nothing prints. Explain why, and give two corrected versions.
Show answer
With the default step of 1, range(10, 0) starts at 10, which is already past the stop value of 0, so the range is empty and the loop body never runs. Corrected: range(10, 0, -1) prints 10 down to 1. Alternatively, loop over range(1, 11) and print 11 - i for each i.