liveBook · Manning

Sys.getsizeof

As explained in Python Workout: 50 ten-minute exercises

sys.getsizeof is a Python function that returns the shallow memory size of an object in bytes.

sys.getsizeof reports an object's shallow memory size in bytes. For lists, it makes hidden growth overhead visible: Python reserves spare pointer slots so many appends avoid immediate reallocation. 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 the loop to compare each list length with sys.getsizeof's reported size as items are appended. section 3.5

Observe capacity steps

The reported size can remain unchanged across several appends, then jump: lengths 1–4 report 96 bytes, length 5 reports 128, and length 9 reports 192. These steps expose reserved capacity rather than a byte-for-byte count of element contents. section 3.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains pointer arrays and spare allocation, but stops short of fine-tuned memory-control techniques.
Examples
Demonstrates a REPL loop that prints list length and reported size after successive appends.
What it assumes
Assumes familiarity with Python lists while explaining their pointer-array representation and growth behavior.
What you can do after
Diagnose/debug with it by observing when list growth triggers larger allocations.
How it connects
Ties Python lists to arrays, pointers, tuples, dynamic allocation, and garbage collection.

Also explained in

Compare how 2 books explain sys.getsizeof →

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.