range vs. list size using getsizeof
Showing that the range object remains the same size regardless of the size of the range, but if we convert it into a list then its memory footprint is proportional to its size. To the number of elements in it.
In this example we have a loop iterating over range(21), but that's only for the convenience, the interesting part is inside the loop. On every iteration we call range() with the current number, then we convert the resulting object into a list of numbers. Finally we print out the current number and the size of both the object returned by range() and the list generated from the object. As you can see the memory usage of the range object remains the same 48 bytes, while the memory usage of the list grows as the list gets longer.
The code we use to demonstrate the memory usage of a range
object vs. the list of numbers generated using it.
import sys
for ix in range(21):
rng = range(ix)
numbers = list(rng)
print("{:>3} {:>3} {:>4}".format(
ix,
sys.getsizeof(rng),
sys.getsizeof(numbers)))
Output:
0 48 64
1 48 96
2 48 104
3 48 112
4 48 120
5 48 128
6 48 136
7 48 144
8 48 160
9 48 192
10 48 200
11 48 208
12 48 216
13 48 224
14 48 232
15 48 240
16 48 256
17 48 264
18 48 272
19 48 280
20 48 288