Skip to main content
Albero Academy

The range() Function

Generate sequences of numbers efficiently for counting loops.

Flow Control7 min

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

CallProduces
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)
range in loops
for i in range(3):
print(i) # 0, 1, 2
for 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:

lazy vs materialised
r = range(5) # a range object, not a list
list(r) # [0, 1, 2, 3, 4] — materialise it
5 in range(1000) # True — membership works without building the list

Key takeaways

  1. 01range(stop), range(start, stop) and range(start, stop, step) generate integer sequences.
  2. 02The stop value is exclusive — range(1, 5) is 1,2,3,4.
  3. 03A negative step counts down.
  4. 04range is lazy and memory-efficient; wrap in list() only when you need the values.
  5. 05range(1, 11) is the idiom for "1 through 10 inclusive".

Finished this chapter?

Mark it complete to track your progress through Python.