Skip to content

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.

Beginner 10 min read·Lesson 251 of 306 in Python Programming

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

Python
import sys, tracemalloc
sys.getsizeof([1, 2, 3])
tracemalloc.start()
... # code to measure
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
  • Objects are freed when unreferenced.
  • getsizeof measures one object.
  • tracemalloc measures code.

Code examples

Object sizes

Python
import sys
print(sys.getsizeof([]) < sys.getsizeof([1, 2, 3]))
print(sys.getsizeof("a" * 100) > sys.getsizeof("a"))
Output
True
True

Exact byte counts differ between Python versions, so the example compares sizes instead of printing them.

Lists grow in steps

Python
import sys
lst = []
sizes = []
for i in range(20):
lst.append(i)
sizes.append(sys.getsizeof(lst))
print(len(set(sizes)) < 20)
Output
True

More examples

Lazy iteration, __slots__ and tracemalloc

Python
import sys
import tracemalloc
squares_list = [n * n for n in range(100_000)]
squares_gen = (n * n for n in range(100_000))
print(sys.getsizeof(squares_list) > 100 * sys.getsizeof(squares_gen))
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
class SlimPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
p, s = Point(1, 2), SlimPoint(1, 2)
print(hasattr(p, "__dict__"), hasattr(s, "__dict__"))
try:
s.z = 3
except AttributeError as e:
print(type(e).__name__)
tracemalloc.start()
data = [str(i) for i in range(10_000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(peak > 100_000)
Output
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:

TextOutput
True
True False
AttributeError
True

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

lines = open("huge.log").readlines()

Prefer

with open("huge.log", encoding="utf-8") as f:
for line in f:
...

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

  1. 1
    Compare the peak memory of summing squares with a list versus a generator using tracemalloc.
  2. 2
    Create 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?
Practise this module