range()
A memory-efficient arithmetic progression — the standard tool for "iterate N times" or "count from a to b".
Demo
range produces the sequence start, start+step, start+2*step, ... stopping BEFORE it reaches stop. That half-open interval matches slicing conventions. Positive step counts up until stop is reached or exceeded; negative step counts down; a step in the wrong direction (say, negative when start < stop) produces an empty range. The demo shows the values as a list for clarity — real code iterates a range object directly.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| start | int | no (0) | The first value in the sequence (inclusive). Omitted → 0. |
| stop | int | yes | The exclusive upper bound. The sequence stops BEFORE reaching this value. |
| step | int | no (1) | The increment between consecutive values. Must be non-zero — 0 raises ValueError. Negative steps count downward. |
Return value
range — A lazy sequence of integers from start (inclusive) to stop (EXCLUSIVE) stepping by step. Not a list — a `range` object that supports iteration, indexing, len(), and slicing. Memory-efficient: only start/stop/step are stored.
Common patterns
for i in range(n): do_step(i)
for i in range(10, 0, -1): print(i)
for i, item in enumerate(items): process(i, item)
r = range(100) first_ten = r[:10] # range(0, 10) every_third = r[::3] # range(0, 100, 3)
Examples
Pitfalls
list(range(1, 5))
list(range(1, 6))
list(range(0, 5, -1))
list(range(5, 0, -1))
range(0, 10, 0)
range(0, 10, 1)
range(5) == [0, 1, 2, 3, 4]
list(range(5)) == [0, 1, 2, 3, 4]
range(0.0, 1.0, 0.1)
[i * 0.1 for i in range(10)]
When to use
- "Do this N times" — the fixed-count loop
- Counting up or down with a fixed step
- Slicing indices you will later apply to a sequence
- Memory-efficient iteration over arithmetic progressions
- Iterating a list with index AND value → enumerate is idiomatic
- Float progressions → comprehension or numpy
- Non-uniform sequences → build a list explicitly
- `range(len(x))` when you actually want the items → iterate x directly
Notes
FAQ
A type. `range(5)` calls the constructor and returns a range OBJECT. This is why `range` is not deprecated even though `list` is a type — both are called like functions.