liveBook · Manning

Memory allocation

As explained in Python Workout: 50 ten-minute exercises

Memory allocation is the process of reserving storage for data during program execution.

Adding values to a Python list is not completely free: Python reserves storage as the list grows and keeps some spare capacity for future appends. This reduces the need to resize on every addition. section 3.5

Inspecting list storage

Use sys.getsizeof to compare a list's length with the storage currently reserved for it. The reported size stays constant across several appends, then jumps when Python allocates another block of space. section 3.5

>>> import sys
>>> mylist = []
>>> for i in range(25):
...     l = len(mylist)
...     s = sys.getsizeof(mylist)
...     print(f'len = {l}, size = {s}')
...     mylist.append(i)

Run this listing to observe list length and allocated size after each append. section 3.5

len = 0, size = 64
len = 1, size = 96
len = 2, size = 96
len = 3, size = 96
len = 4, size = 96
len = 5, size = 128
len = 6, size = 128
len = 7, size = 128
len = 8, size = 128
len = 9, size = 192
len = 10, size = 192
len = 11, size = 192
len = 12, size = 192
len = 13, size = 192
len = 14, size = 192
len = 15, size = 192
len = 16, size = 192
len = 17, size = 264
len = 18, size = 264
len = 19, size = 264
len = 20, size = 264
len = 21, size = 264
len = 22, size = 264
len = 23, size = 264
len = 24, size = 264

Compare the output to see spare capacity and stepwise allocation rather than one-byte-per-item growth. section 3.5

Treat these details as useful background for optimization or implementation awareness, not as routine application concerns. Python's garbage collector generally handles memory well, while offering limited fine-grained control. section 3.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains spare list capacity and inspection with sys.getsizeof, but stops short of allocator internals or garbage-collector control.
Examples
Demonstrates repeated list appends, sys.getsizeof measurements, and output showing stepwise storage increases.
What it assumes
Assumes familiarity with Python lists, len, append, loops, imports, and formatted output.
What you can do after
Evaluate list storage growth with sys.getsizeof and recognize when allocation details matter for optimization.
How it connects
Connects memory allocation with Python lists, appending, sys.getsizeof, garbage collection, and language implementation.

Also explained in

Compare how 11 books explain memory allocation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.