Sub topic 5
range is a lazy sequence, not a list
This chapter assumes you can write a basic for loop, know how range(start, stop, step) picks its numbers, and are comfortable with list indexing and slicing. Here you will see what a range object is, what it can do, and where it differs from a list.
What lazy means
Calling range(1_000_000) does not create a million integers. It creates a small object that remembers three numbers: start, stop and step. Every value is calculated from those three numbers when you ask for it.
import sys
small = range(10)
huge = range(10**12)
print(sys.getsizeof(small) == sys.getsizeof(huge)) # True
print(huge.start, huge.stop, huge.step) # 0 1000000000000 1Both objects have the same size, because each stores only three integers. A list of 10**12 items would need terabytes of memory. A for loop over huge would still take a very long time to finish. Laziness saves memory. It does not make the loop itself shorter.
The three attributes start, stop and step are read-only. If you omit start or step, you get the defaults 0 and 1.
A sequence, not just an iterator
Python distinguishes two ideas that are easy to mix up:
- An iterator produces values one at a time and cannot go back.
- A sequence has a length, supports indexing, and can be traversed repeatedly.
A range is a sequence. That is why it supports more than a generator does.
r = range(0, 20, 5)
print(len(r)) # 4
print(r[2]) # 10
print(r[-1]) # 15
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]Each operation works by arithmetic on start, stop and step:
len(r)is calculated from the three numbers, not by counting.r[i]returnsstart + i * stepafter checking thatiis in bounds.- Slicing returns a new
range, not a list. Herer[1:3]is another lazy object with its ownstart,stopandstep. reversed(r)walks the same values from the end, with no copy.
A range also has the count() and index() methods, like other sequences:
r = range(10, 50, 10)
print(r.index(30)) # 2
print(r.count(30)) # 1
print(r.count(35)) # 0Because a range never repeats a value, count() returns only 0 or 1.
Fast membership tests
For integers, x in range(...) does not scan the values. Python checks whether x lies between the bounds and whether (x - start) divides evenly by step. The cost is the same whether the range has ten items or a trillion.
big = range(0, 10**12, 7)
print(7_000_000_000 in big) # True
print(7_000_000_001 in big) # FalseBoth checks finish immediately. The same test on a list of that size would not even fit in memory.
The fast path applies only to exact int values. Other types fall back to comparing against each item in turn:
print(3.0 in range(5)) # True, found by scanning and comparing 3.0 == 3This still gives the right answer. It is slow only on very large ranges.
Large bounds and the length limit
A range can describe more values than Python can count with its internal length type. Indexing still works, but len() fails:
r = range(10**30)
print(r[5]) # 5
print(10**29 in r) # True
try:
len(r)
except OverflowError:
print("too long for len()")You will rarely hit this. It is a useful reminder that a range holds a description of the values, not the values themselves.
What a range cannot do
A range is immutable. You cannot change its contents, because they do not exist as stored items.
r = range(5)
try:
r[0] = 99
except TypeError as e:
print(e) # 'range' object does not support item assignment
print(hasattr(r, "append")) # FalseA range is also not an iterator. You cannot call next() on it directly. You first ask it for an iterator with iter():
r = range(3)
try:
next(r)
except TypeError as e:
print(e) # 'range' object is not an iterator
it = iter(r)
print(next(it)) # 0The difference matters when you loop twice. An iterator is used up after one pass. A range hands out a fresh iterator each time, so it can be looped over repeatedly.
r = range(3)
print(list(r)) # [0, 1, 2]
print(list(r)) # [0, 1, 2] again
it = iter(range(3))
print(list(it)) # [0, 1, 2]
print(list(it)) # [] because the iterator is exhaustedRanges compare by the values they describe
Two ranges are equal when they produce the same values, even if their arguments differ. A range never equals a list, even one with the same items.
print(range(0, 3, 2) == range(0, 4, 2)) # True: both give 0, 2
print(range(0) == range(5, 5)) # True: both are empty
print(range(3) == [0, 1, 2]) # False: different types
print(list(range(3)) == [0, 1, 2]) # TrueIf you need to compare a range with a list, convert one side with list() first.
Only integers, and a non-zero step
The three arguments must be integers. Floats are rejected, even if they look whole. A step of zero would never move, so it is an error too.
for bad in [lambda: range(0, 1, 0.1), lambda: range(2.0), lambda: range(0, 5, 0)]:
try:
bad()
except (TypeError, ValueError) as e:
print(type(e).__name__, "-", e)For fractional steps, compute the values from integers instead:
values = [i / 10 for i in range(0, 11, 2)]
print(values) # [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]When to convert a range to a list
Keep the range when you only loop, test membership, index, or slice. Convert with list(range(...)) when you need a real list. Common reasons are:
- You want to modify the values, for example with
append,removeor item assignment. - You want to see the values in the REPL.
print(range(5))showsrange(0, 5), not the numbers. - You need to mix the values with other data in a mutable container.
numbers = list(range(1, 6))
numbers.append(6)
numbers[0] = 100
print(numbers) # [100, 2, 3, 4, 5, 6]Do not write for i in list(range(n)). It builds a list that the loop never needed, and it uses memory proportional to n for no benefit.
Summary of differences
| Feature | `range` | `list` |
|---|---|---|
| Memory use | Constant: three integers | Grows with the number of items |
| Holds values | No, computes them | Yes, stores them |
| Mutable | No | Yes |
| `len()`, indexing, slicing | Yes (slicing returns a range) | Yes (slicing returns a list) |
| Membership test on integers | Constant time | Linear time |
| Can hold non-integers | No | Yes |
| Can be looped repeatedly | Yes | Yes |
Exercise
Predict the output, then run it to check. r = range(2, 30, 4) print(len(r)) print(r[-1]) print(r[1:4]) print(18 in r) print(19 in r) print(r == range(2, 31, 4))
Show answer
The values are 2, 6, 10, 14, 18, 22, 26. The output is: 7 26 range(6, 18, 4) True False True The last line is True because range(2, 31, 4) describes the same seven values (30 is not reached since 2 + 4 * 7 = 30 is excluded by stop=31 only if it is below 31, so check: 30 is a value only if 30 - 2 is divisible by 4, and 28 / 4 = 7, so 30 IS included). Therefore range(2, 31, 4) contains 30 as an eighth value and the comparison is False, and the len and r[-1] lines above stay unchanged. Correct final line: False.
Exercise
A script runs for _ in range(10**9): pass and you want to know if 123456789 would be one of the values produced by range(0, 10**9, 3). Write a one-line check that answers this without looping, and explain why it is fast.
Show answer
print(123456789 in range(0, 10**9, 3)). It is fast because Python tests integer membership with arithmetic: it checks the number is between start and stop, and that (123456789 - 0) is divisible by 3. It never walks the values. The result is True, since 1+2+3+4+5+6+7+8+9 = 45 is divisible by 3.