Module 17 · Advanced Python Concepts — topic 5 of 14
Memory management
How Python manages memory for you: objects on a private heap, reference counting, object sizes with sys.getsizeof, list over-allocation, generators versus lists, __slots__, and measuring memory with tracemalloc.
Learning objectives
- Describe how CPython allocates and frees objects
- Compare the memory cost of different approaches
- Measure memory use with sys.getsizeof and tracemalloc
Definition
Memory management is how Python allocates memory for objects and frees it when they are no longer used. CPython uses reference counting plus a cycle-detecting garbage collector, so programmers rarely free memory explicitly.
Introduction
Python hides memory management, which is why it's easy to learn. But when a program processes millions of records, knowing how memory is used decides whether it runs or crashes.
Why it matters
Choosing lazy iteration, compact data structures and avoiding unnecessary copies can reduce memory use by orders of magnitude.
Detailed explanation
Every Python value is an object stored on a private heap managed by the interpreter. Names and containers hold references to these objects.
CPython counts references to each object. When the count drops to zero — the last name is deleted or reassigned — the object is freed immediately.
Reference cycles (objects referring to each other) never reach zero on their own; the garbage collector finds and frees them (next lesson).
sys.getsizeof(obj) reports an object's own size in bytes, not the size of objects it refers to. Exact numbers vary between Python versions and platforms.
Lists over-allocate: they reserve extra slots so that append is usually fast, growing in steps rather than one slot at a time.
Generators produce values one at a time instead of storing them all, so their memory use stays small regardless of length.
__slots__ declares a fixed set of attributes, removing each instance's __dict__ and saving memory when creating many small objects.
tracemalloc measures memory allocated by Python code, including the peak, which helps find memory-hungry steps.
Syntax
- Objects are freed when unreferenced.
- getsizeof measures one object.
- tracemalloc measures code.
Code examples
Object sizes
True True
Exact byte counts differ between Python versions, so the example compares sizes instead of printing them.
Lists grow in steps
True
More examples
Lazy iteration, __slots__ and tracemalloc
True True False AttributeError True
Step-by-step explanation
- The list stores 100,000 results; the generator stores only its current state, so it is hundreds of times smaller.
- SlimPoint has no per-instance __dict__, and adding undeclared attributes fails.
- tracemalloc confirms that building 10,000 strings allocated well over 100 KB.
Expected output
Running “Lazy iteration, __slots__ and tracemalloc” prints exactly:
Practical applications
- Processing log files line by line instead of loading them whole.
- Using __slots__ for millions of small objects in simulations.
Best practices
- Iterate lazily over large data.
- Measure before optimising.
- Use __slots__ only when you create very many instances.
Common mistakes
Loading everything into memory
Avoid
Prefer
Iterating processes one line at a time with constant memory.
Important notes
- Other Python implementations (PyPy, Jython) manage memory differently; reference counting is a CPython detail.
Key takeaways
- CPython frees objects when their reference count reaches zero.
- getsizeof and tracemalloc measure memory.
- Generators and __slots__ reduce memory use.
Try it yourself
- 1Compare the peak memory of summing squares with a list versus a generator using tracemalloc.
- 2Create 100,000 Point and SlimPoint objects and compare memory with tracemalloc.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
16 questions cover the “Advanced Python Concepts” module. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?
- AdvancedWhat is printed?
- AdvancedWhat is printed?