range generates a sequence of integers on demand. It's the standard way to repeat something a fixed number of times, and it's memory-efficient — it computes each number as needed rather than storing them all.
The three forms
| Call | Produces |
|---|---|
range(5) | 0 1 2 3 4 (stop only, starts at 0) |
range(2, 8) | 2 3 4 5 6 7 (start, stop) |
range(0, 10, 2) | 0 2 4 6 8 (start, stop, step) |
range(5, 0, -1) | 5 4 3 2 1 (negative step counts down) |
for i in range(3):print(i) # 0, 1, 2for i in range(1, 11):print(i * i) # squares 1 to 100
Stop is exclusive
range is lazy
range doesn't build a list — it's a lazy object that yields numbers as you loop. That's why range(1_000_000_000) is instant and uses almost no memory. Wrap it in list() only when you actually need the values as a list:
r = range(5) # a range object, not a listlist(r) # [0, 1, 2, 3, 4] — materialise it5 in range(1000) # True — membership works without building the list
Key takeaways
- 01range(stop), range(start, stop) and range(start, stop, step) generate integer sequences.
- 02The stop value is exclusive — range(1, 5) is 1,2,3,4.
- 03A negative step counts down.
- 04range is lazy and memory-efficient; wrap in list() only when you need the values.
- 05range(1, 11) is the idiom for "1 through 10 inclusive".
