← Back to Python, page 2

python-0039 · Easy fresher

What does range() return, and why is 'for i in range(len(items))' often a code smell?

range returns a lazy, immutable sequence of integers that supports len, indexing and fast membership without storing every number. Looping with range(len(items)) only to index items is usually clearer as for item in items, or for i, item in enumerate(items) when the index is needed.

Full answer
python
r = range(0, 20, 5)
print(r, list(r), len(r), r[2], 15 in r, 7 in r)
import sys
print(sys.getsizeof(range(10**9)) < 100)
items = ["pen", "ink", "pad"]
for i in range(len(items)):
    print(i, items[i])
for i, item in enumerate(items):
    print(i, item)
print(list(range(5, 0, -2)))

Output:

text
range(0, 20, 5) [0, 5, 10, 15] 4 10 True False
True
0 pen
1 ink
2 pad
0 pen
1 ink
2 pad
[5, 3, 1]

A range of a billion numbers takes only a few dozen bytes because values are computed on demand, and 15 in r is answered arithmetically rather than by scanning. The two loops print the same thing, but the enumerate version avoids repeated indexing and works with any iterable, not only sequences. Negative steps count down, and the stop value is excluded as in slicing. Use range(len(...)) when you truly need to modify items by position or compare neighbours.

python
r = range(0, 20, 5)
print(r, list(r), len(r), r[2], 15 in r, 7 in r)
import sys
print(sys.getsizeof(range(10**9)) < 100)
items = ["pen", "ink", "pad"]
for i in range(len(items)):
    print(i, items[i])
for i, item in enumerate(items):
    print(i, item)
print(list(range(5, 0, -2)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • range is lazy and constant-size
  • Supports len, indexing and fast membership
  • Prefer direct iteration or enumerate
  • Stop is exclusive
  • Negative steps count down

Common mistakes

  • Indexing in loops unnecessarily
  • Calling list(range(...)) for large ranges

Follow-ups

  • How do you loop over adjacent pairs?
  • How would you iterate backwards?

Tips

  • Show enumerate as the alternative