Sub topic 16
Common range mistakes and how to avoid them
This chapter assumes you can write a for loop, know range() with one, two or three arguments, and understand that a range object is a lazy sequence. Here we collect the mistakes that appear most often and show the fix for each.
Mistake 1: forgetting that stop is excluded
range(1, 5) yields 1, 2, 3, 4. It never yields 5. If you want to include the last number, add one to the stop value.
print(list(range(1, 5))) # [1, 2, 3, 4]
print(list(range(1, 5 + 1))) # [1, 2, 3, 4, 5]A useful check: len(range(a, b)) equals b - a when the step is 1. Count the items you expect and compare.
Mistake 2: counting backwards without a negative step
If start is larger than stop and the step is positive, the range is empty. No error is raised, so the loop silently does nothing.
print(list(range(5, 0))) # []
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]
print(list(range(5, -1, -1))) # [5, 4, 3, 2, 1, 0]When counting down, the stop value is also excluded. To include 0, stop at -1.
Mistake 3: using a float
range() accepts only integers. Passing a float raises TypeError. A step of 0 raises ValueError.
try:
range(0, 1, 0.1)
except TypeError as e:
print("TypeError:", e)
try:
range(0, 10, 0)
except ValueError as e:
print("ValueError:", e)For fractional steps, compute the value from an integer counter:
for i in range(5):
print(i / 10)Mistake 4: `range(len(...))` when you do not need an index
Looping over indexes just to read each item is longer and easier to get wrong than looping over the items.
colors = ["red", "green", "blue"]
# Avoid
for i in range(len(colors)):
print(colors[i])
# Prefer
for color in colors:
print(color)
# If you need the index too
for i, color in enumerate(colors):
print(i, color)Use range(len(...)) only when you need to assign to positions, or when you step through indexes in an unusual way.
Mistake 5: expecting a list
A range object prints as range(0, 5), not as its values. Convert it with list() only when you need a real list, for example to print it or to modify it.
r = range(5)
print(r) # range(0, 5)
print(list(r)) # [0, 1, 2, 3, 4]Do not call list() just to loop. The loop can use the range directly, and doing so avoids building a large list in memory.
Mistake 6: changing the range inside the loop
Reassigning the loop variable does not change the next value. The for statement takes the next item from the range on every pass.
for i in range(3):
i = i * 10
print(i) # 0, 10, 20Likewise, changing a variable you used as an argument after the loop has started has no effect, because range() was already evaluated once.
n = 3
for i in range(n):
n = 10
print(i) # still 0, 1, 2If the number of iterations must change while the loop runs, use a while loop.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Last value missing | Stop is excluded | Use `stop + 1` |
| Loop body never runs | Start greater than stop with a positive step | Add a negative step |
| `TypeError` | Float argument | Use integers and divide inside the loop |
| `ValueError` | Step of 0 | Use a non-zero step |
| Printed `range(0, 5)` | It is not a list | Wrap in `list()` |
Exercise
Write a loop that prints the numbers 10, 8, 6, 4, 2, 0 using range(). Which three arguments do you pass?
Show answer
Use for i in range(10, -1, -2): print(i). The start is 10, the stop is -1 so that 0 is included, and the step is -2. Using a stop of 0 would leave 0 out.