Sub topic 5
range is a lazy sequence, not a list
This chapter assumes you can write a basic for loop, call range() with one, two, or three arguments, and run a Python 3 script. Here you will see what a range object is, why it uses almost no memory, and which list-like operations it supports.
A range stores three numbers
When you call range(1_000_000), Python does not create a million integers. It creates a small object that remembers start, stop, and step. Each value is computed from those three numbers when you ask for it. This is called lazy evaluation.
import sys
big_range = range(1_000_000)
big_list = list(big_range)
print(sys.getsizeof(big_range)) # a few dozen bytes
print(sys.getsizeof(big_list)) # several megabytes
print(type(big_range)) # <class 'range'>The exact byte counts depend on your Python build. The size of the range object stays the same whether it covers ten numbers or ten billion.
It still behaves like a sequence
A range is not a list, but it supports the read-only operations you would expect from one. It does this without building the values first.
r = range(0, 20, 5)
print(len(r)) # 4
print(r[2]) # 10
print(15 in r) # True
print(7 in r) # False
print(r[1:3]) # range(5, 15, 5)
print(list(reversed(r))) # [15, 10, 5, 0]Three points are worth noting:
- Indexing computes the value with arithmetic:
start + index * step. Negative indexes work, sor[-1]is15. - Slicing returns another
range, not a list. The slicer[1:3]is a new lazy object with different bounds. - A membership test such as
15 in ralso uses arithmetic for integers. It does not scan the values, so it is fast even for huge ranges.
What a range cannot do
Because a range only describes a pattern of integers, it is immutable and limited to integer arithmetic.
r = range(5)
try:
r[0] = 99
except TypeError as error:
print(error) # 'range' object does not support item assignment
print(hasattr(r, "append")) # False
print(r == range(0, 5)) # True
print(r == [0, 1, 2, 3, 4]) # FalseYou cannot assign to an element or call append(). Two ranges are equal when they describe the same sequence of values. A range never equals a list, even when the numbers match.
Convert to a list when you need a real, changeable collection:
numbers = list(range(1, 6))
numbers.append(6)
print(numbers) # [1, 2, 3, 4, 5, 6]Why this matters for loops
Use range directly in a for loop and avoid wrapping it in list() first. The wrapper allocates every value for no benefit.
total = 0
for n in range(1, 1_000_001):
total += n
print(total) # 500000500000Exercise
What do len(r) and r[-1] return for r = range(10, 0, -3), and does Python build a list of the values to answer?
Show answer
The range produces 10, 7, 4, 1, so len(r) is 4 and r[-1] is 1. Python does not build a list. It computes both answers from start, stop, and step.
Exercise
Why is 10**12 in range(0, 10**13, 2) fast, and what does it return?
Show answer
Python checks the membership with arithmetic on start, stop, and step, so it does not look at each value. It returns True because 10**12 is even and lies within the bounds.