Sub topic 16
Common range mistakes and how to avoid them
This chapter assumes you know how range(start, stop, step) works, that a range object is a lazy sequence, and how for loops, enumerate() and zip() behave. Most range bugs come from a few misunderstandings. Each section below shows the mistake, what Python does, and the fix.
Off-by-one errors with the stop value
range includes start and excludes stop. That is a deliberate half-open interval, and it causes the most common bug: stopping one item early.
print(list(range(1, 10))) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(1, 11))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(len(range(3, 8))) # 5The half-open design gives you two useful rules:
- With a step of 1, the number of items is
stop - start. - Two ranges that share a boundary join without overlap:
range(0, 5)followed byrange(5, 10)covers 0 to 9 exactly once.
When you want to include the last value, add 1 to stop. Write range(1, n + 1) to count from 1 through n. Do not reach for range(1, n) and hope.
Counting backwards with the wrong step
range only moves in the direction of the step. If the step points away from stop, the range is empty and no error is raised.
print(list(range(5, 0))) # [] (step defaults to +1, so it never reaches 0)
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]
print(list(range(5, -1, -1))) # [5, 4, 3, 2, 1, 0]
print(list(reversed(range(6)))) # [5, 4, 3, 2, 1, 0]A silent empty loop is hard to spot. When a loop body never runs, print the range and check the sign of the step.
Counting down also shifts the exclusive bound. range(5, 0, -1) stops at 1, not 0. To include 0, set stop to -1. If range(n - 1, -1, -1) looks hard to read, use reversed(range(n)), which gives the same values and says what you mean.
Passing floats
range accepts only integers, and that applies to all three arguments.
try:
range(0, 1, 0.1)
except TypeError as error:
print(error) # 'float' object cannot be interpreted as an integer
try:
range(5.0)
except TypeError:
print("5.0 is rejected too")A float that looks whole, such as 5.0, is still rejected. This often appears after a division: len(items) / 2 is a float even when the result is whole. Use // for integer division, or int() when you really want to truncate.
To step through fractional values, loop over an integer range and scale it:
print([i / 10 for i in range(4)]) # [0.0, 0.1, 0.2, 0.3]Do not build a float sequence by adding 0.1 repeatedly. Rounding error accumulates, so the last value can land just above or below the bound you expected. Scaling an integer counter avoids this because each value is computed from scratch.
A step of zero
A step of 0 would never move, so range rejects it.
try:
range(0, 10, 0)
except ValueError:
print("step must not be zero")This usually appears when the step is computed, for example (stop - start) // parts with more parts than distance. Validate or clamp the step before calling range, for example max(1, step).
Treating a range as a list
A range object is a sequence, but it is not a list. Printing it shows the arguments, not the values, and it cannot be changed.
r = range(5)
print(r) # range(0, 5)
try:
r.append(5)
except AttributeError:
print("ranges have no append")
values = list(r)
values.append(5)
print(values) # [0, 1, 2, 3, 4, 5]Call list(r) only when you need a mutable copy or want to see the values. For plain iteration, membership tests, len(), and indexing, keep the range. The memory cost is constant. range(10**12) is created instantly, while list(range(10**12)) would try to allocate terabytes.
big = range(10**12)
print(len(big)) # 1000000000000
print(10**11 in big) # True, answered by arithmetic and not by scanningOne edge case: len() raises OverflowError if the length exceeds sys.maxsize. Iteration and in still work for such ranges.
Expecting the range to change inside the loop
The arguments to range are evaluated once, when the loop starts. Changing the variable you used afterwards has no effect on the iteration.
n = 3
count = 0
for i in range(n):
n += 1
count += 1
print(count, n) # 3 6The loop ran three times even though n grew. If the number of iterations must depend on changing data, use a while loop. If the data is a list you are modifying, see the earlier chapter on why you should not change a list while looping over it.
Index loops that run past the end
range(len(data)) produces valid indexes 0 to len(data) - 1. Problems start when the body looks at a neighbour.
data = [3, 8, 15]
for i in range(len(data) - 1):
print(data[i], data[i + 1])
# 3 8
# 8 15With range(len(data)), the last pass would evaluate data[3] and raise IndexError. Subtracting 1 fixes it, and an empty list is safe because range(-1) is empty.
There is a cleaner way that removes the arithmetic. zip stops at the shorter input, so it never goes past the end:
data = [3, 8, 15]
for current, following in zip(data, data[1:]):
print(current, following)More generally, if the body only uses i to read data[i], you do not need range(len(...)). Loop over the items directly, or use enumerate() when you also need the position.
Using the loop variable after an empty range
The loop variable is only bound when the body runs at least once. After for j in range(0): pass, the name j does not exist, so reading it raises NameError. If code after the loop depends on the variable, give it a default first:
last = None
for last in range(0):
pass
print(last) # NoneQuick diagnosis table
| Symptom | Likely cause | Fix |
|---|---|---|
| Loop misses the final value | Exclusive `stop` | Use `stop + 1`, or recheck whether you need it |
| Loop body never runs | Step points away from `stop` | Use a negative step, or `reversed(range(...))` |
| `TypeError` about float | Float argument, often from `/` | Use `//` or `int()`, or scale an integer range |
| `ValueError` from `range` | Step is 0 | Validate the computed step |
| `AttributeError` on `append` or `sort` | Range is not a list | Convert with `list(r)` |
| `IndexError` in the body | `data[i + 1]` on the last index | Use `len(data) - 1`, or `zip(data, data[1:])` |
| `NameError` after the loop | Range was empty | Set a default before the loop |
Choosing the right arguments
A defensive habit
When a range loop behaves oddly, test the sequence before the loop body. Print list(range(...)) for small inputs, and check the first value, the last value, and the length. Those three facts expose most of the mistakes above in seconds.
def describe(r):
values = list(r)
if not values:
return "empty"
return f"first={values[0]}, last={values[-1]}, length={len(values)}"
print(describe(range(5, 0))) # empty
print(describe(range(5, 0, -1))) # first=5, last=1, length=5
print(describe(range(1, 11, 3))) # first=1, last=10, length=4Exercise
A student wants to print the even numbers from 10 down to 0, including both ends, and writes for n in range(10, 0, -2): print(n). What does it print, and how do you fix it?
Show answer
It prints 10, 8, 6, 4, 2 and misses 0, because stop is exclusive. Change the stop value to -1 so that 0 is included: range(10, -1, -2). This yields 10, 8, 6, 4, 2, 0.
Exercise
The code for i in range(len(prices) / 2): print(prices[i]) fails with a TypeError. Explain why, and give two ways to fix it.
Show answer
The / operator always returns a float, and range accepts only integers. Use integer division, range(len(prices) // 2), or convert explicitly with range(int(len(prices) / 2)). If you only want the first half of the items, you could also loop over the slice prices[:len(prices) // 2] directly.