Memory Management in Python
Every chapter so far has focused on what Python code does. This chapter is about something quieter running underneath every one of those chapters the whole time: how Python actually keeps track of every object it creates, and when it decides that object can be thrown away. Understanding it explains a genuinely confusing bug (the mutable default argument gotcha), a real design trade-off (__slots__), and gives you the tools to actually measure — not guess — where a program's memory is going.
How to read this chapter
- Sub-topic 1 covers what happens when Python creates an object, and reference counting — the mechanism behind it, using
sys.getrefcount(). - Sub-topic 2 covers reference cycles — a case reference counting alone can't handle — and the cyclic garbage collector that cleans them up.
- Sub-topic 3 covers the mutable default argument gotcha, built from the reference/object model Sub-topics 1-2 just established, not as a rule to memorize.
- Sub-topic 4 covers
__slots__— what it saves, and what it costs. - Sub-topic 5 covers memory profiling basics:
sys.getsizeof()for one object,tracemallocfor a whole block of code. - Sub-topic 6 ties everything back to Chapter 17's generators as the memory-efficient alternative to materializing a full list.
- A note on the numbers in this chapter: every byte count and refcount shown was actually measured by running the exact code on this course's build system (Python 3.14.4). Your own numbers may differ slightly by Python version, platform, or even which line ran right before — the pattern (which approach uses more or less memory) is what matters, not memorizing an exact byte count.
1. How Python manages memory & reference counting
- Every object Python creates keeps a running count of how many references point to it — its reference count.
- Assigning a variable, appending to a list, or passing an argument all add a reference; deleting a variable or letting it go out of scope removes one.
- The instant an object's reference count hits zero, Python frees it immediately — no waiting, no separate cleanup pass.
del, reassignment, a variable going out of scope) decrements it. When the count reaches zero, nothing in the program can reach that object anymore, so Python deallocates it right away.
sys.getrefcount() makes this counter directly visible.
One detail before the first example: calling
sys.getrefcount(obj) itself temporarily creates one more
reference to obj (as the function's own argument), so
the number it reports is always one higher than you might expect
from counting references in your own code:
import sys
a = [1, 2, 3]
print("refcount right after creation:", sys.getrefcount(a))
b = a
print("refcount after b = a:", sys.getrefcount(a))
del b
print("refcount after del b:", sys.getrefcount(a))
refcount right after creation: 2
refcount after b = a: 3
refcount after del b: 2
Thought process: the goal here isn't just "call getrefcount()" — it's picking a sequence of operations (create, alias, delete) that makes the counter visibly move, so the concept is observable rather than asserted. An experienced dev would also anticipate the off-by-one surprise and print enough intermediate steps to make it self-explanatory, rather than printing one final number and leaving the reader to guess why it looks wrong.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a short Python script using only the standard library that demonstrates how sys.getrefcount() changes as references to an object are added and removed. Create a list `a`, print its refcount, assign `b = a` and print the refcount again (it should go up by 1), then `del b` and print it a third time (it should drop back to the previous value). Also print one comment explaining why the very first reading is 2, not 1 (because calling getrefcount() itself creates one temporary reference).
The count starts at 2, not 1 — one
reference is a itself, the other is the temporary
reference getrefcount() holds while it runs. Assigning
b = a adds a second real reference, bumping the total
to 3; del b removes it again, back down to
2. Nothing was ever printed about the list being freed
here, because it never reached zero — a is still
holding on.
__del__?
A class can define a __del__ method that Python calls right when an instance's reference count hits zero — a hook for "this object is about to be destroyed." It's used sparingly in real code (mostly for closing external resources as a last-resort safety net) and is the easiest way to actually observe reference counting in action, which Sub-topic 2 uses on purpose.
- Reference counting is Python's default, always-on memory management strategy — every object has one, all the time.
sys.getrefcount(obj)reports the count, but always one higher than "real" references, since calling it adds a temporary one of its own.- The moment an object's count reaches zero, it's deallocated immediately — not on some later cleanup pass.
Go Deeper: is reference counting unique to Python?
No — it's a common memory management strategy used by other languages and systems too (Swift and Objective-C's ARC, for example). What's specific to CPython (the reference Python implementation nearly everyone uses) is combining reference counting as the primary mechanism with a separate cyclic garbage collector as a backup for the one case reference counting can't handle on its own — covered next.
- Every object tracks how many references point to it; that count goes up and down as references are created and removed.
sys.getrefcount(obj)reports it, always one higher than expected because the call itself holds a temporary reference.- An object is freed the instant its reference count reaches zero.
2. Reference cycles & the garbage collector
- A reference cycle is two or more objects that reference each other, directly or indirectly — their combined reference count never reaches zero on its own, even when nothing outside the cycle can reach them.
- Python's cyclic garbage collector (the
gcmodule) exists specifically to find and free these cycles, running periodically alongside reference counting. gc.collect()can be triggered manually;gc.get_count()shows how close the collector is to running automatically.
Before the code: here's the exact shape of the problem, two objects holding a reference to each other:
+----------+ +----------+
| Node A | -------> | Node B |
| .partner | | .partner |
+----------+ <------- +----------+
Nothing outside this pair points to either node anymore,
but A still holds a reference to B, and B still holds a
reference to A -- so neither refcount ever reaches zero
on its own.
With that picture in place, here's the cycle built in real code,
with gc deliberately turned off first so reference
counting is left entirely on its own:
import gc
class Node:
def __init__(self, name):
self.name = name
self.partner = None
def __del__(self):
print(f" Node {self.name} destroyed")
def make_cycle():
a = Node("A")
b = Node("B")
a.partner = b
b.partner = a
gc.disable()
print("Calling make_cycle()...")
make_cycle()
print("make_cycle() returned -- both Nodes should be unreachable now,")
print("but refcounting alone can't free them (each still holds a")
print("reference to the other through .partner).")
print()
print("Running gc.collect()...")
collected = gc.collect()
print(f"gc.collect() freed {collected} objects total this pass")
gc.enable()
Calling make_cycle()...
make_cycle() returned -- both Nodes should be unreachable now,
but refcounting alone can't free them (each still holds a
reference to the other through .partner).
Running gc.collect()...
Node A destroyed
Node B destroyed
gc.collect() freed 23 objects total this pass
Thought process: proving a cycle can't self-free needs a way to actually observe destruction, so __del__ with a print statement is the right instrumentation choice here — without it, "the objects are still alive" would just be an assertion. Disabling gc first is also deliberate: it isolates reference counting's real behavior on its own, before showing the collector as the fix, rather than blurring the two mechanisms together in one run.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python script using only the gc module that demonstrates a reference cycle refcounting alone can't free. Define a class Node with a __del__ method that prints "Node {name} destroyed". Write a function make_cycle() that creates two Node instances, sets each one's .partner attribute to the other, and returns nothing (so both go out of scope when the function returns). Call gc.disable() first, call make_cycle(), and show that no destruction message prints. Then call gc.collect() and show the destruction messages appear only after that call. Re-enable gc at the end.
Notice what happened, in order: make_cycle() returned
with no destruction messages at all — both nodes are
genuinely unreachable from anywhere in the program, yet neither
__del__ ran, because each node's refcount is still 1
(held by its partner). Only once gc.collect() actually
runs does it detect the cycle and free both nodes together —
note the 23 figure includes other unrelated garbage
the collector swept up in the same pass, not just these two nodes;
the exact number varies run to run and isn't the point — what
matters is that the two destruction messages only appear after
gc.collect(), never before.
gc.get_count()?
CPython's cyclic collector groups tracked objects into three generations (0, 1, 2) based on how long they've survived. New objects start in generation 0; objects that survive a collection get promoted to the next generation. gc.get_count() returns a tuple of how many allocations have happened in each generation since its last collection — younger generations are collected far more often than older ones, since most objects (and most cycles) die young.
import gc
print("gc.get_count() right now:", gc.get_count())
print("gc.get_threshold():", gc.get_threshold())
gc.get_count() right now: (0, 0, 0)
gc.get_threshold(): (700, 10, 10)
gc.get_threshold() shows what triggers an automatic
collection: once generation 0 has accumulated roughly 700 more
allocations than deallocations, Python runs a collection pass on
its own — this is why cycles usually do get cleaned up
eventually without anyone calling gc.collect()
manually; the collector runs periodically in the background,
threaded through normal program execution.
- A reference cycle is two or more objects referencing each other so their refcounts never reach zero on their own, even when unreachable from the rest of the program.
- The
gcmodule's cyclic collector detects and frees these cycles; it runs automatically and can also be triggered manually withgc.collect(). - Objects are grouped into generations (0, 1, 2); younger generations are collected far more often, since most garbage (cyclic or not) is short-lived.
Go Deeper: can you turn the cyclic collector off permanently?
Yes, with gc.disable() — but doing so in a real
long-running program (a web server, a background worker) risks a
slow memory leak from any cycle that ever forms, since nothing
would ever free it. It's occasionally done as a performance
optimization in short-lived scripts that create no cycles at all,
but it's a deliberate, informed trade-off, not a default choice.
- A reference cycle keeps two or more objects' refcounts above zero even when nothing else in the program can reach them.
- The cyclic garbage collector (
gcmodule) finds and frees these cycles;gc.collect()triggers it manually. gc.get_count()/gc.get_threshold()show how close the next automatic collection is, across three generations.
3. The mutable default argument gotcha
- A default argument value is created once, at function-definition time — not once per call.
- If that default is a mutable object (a list, dict, or set), every call that doesn't override it shares the exact same object, and mutations pile up across calls.
- This isn't a special-case rule to memorize — it's a direct, predictable consequence of the reference/object model Sub-topics 1-2 already covered.
Here's the broken version, run three times in a row:
def add_item_broken(item, cart=[]):
cart.append(item)
return cart
print(add_item_broken("apple"))
print(add_item_broken("banana"))
print(add_item_broken("cherry"))
['apple']
['apple', 'banana']
['apple', 'banana', 'cherry']
Every call was supposed to start from a fresh, empty cart —
instead, each one keeps appending to the same list. Here's why,
traced back to what def actually does: cart=[]
builds exactly one empty list object the moment Python reads
this def statement, and stores a reference to
it as the parameter's default. Every subsequent call that omits
cart reuses that identical reference — not a
copy, the literal same object, still holding whatever was appended
to it last time. This is directly checkable:
print("id check -- same default object reused every call:")
print(id(add_item_broken.__defaults__[0]))
add_item_broken("x")
print(id(add_item_broken.__defaults__[0]))
id check -- same default object reused every call:
128675401047424
128675401047424
__defaults__?
Every function object stores its parameters' default values in a tuple accessible as func.__defaults__. It's built once, when the def statement runs, and stays fixed for the lifetime of the function object — which is exactly why id(add_item_broken.__defaults__[0]) reports the same address before and after a call, proving it really is the same list object, not a fresh one.
The fix follows directly once the cause is clear: use None
as a harmless, immutable placeholder default, and build a genuinely
new mutable object inside the function body every time it's needed:
def add_item_fixed(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item_fixed("apple"))
print(add_item_fixed("banana"))
print(add_item_fixed("cherry"))
['apple']
['banana']
['cherry']
Thought process: the fix has to preserve the function's original intent — an optional cart argument that defaults sensibly — while removing the shared mutable state. None as a sentinel is the standard idiom precisely because it's immutable, so reusing it as a default is always safe; the real work happens in the "if cart is None" line, which is what actually manufactures a fresh list per call.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
This function has the classic mutable default argument bug:
def add_item_broken(item, cart=[]):
cart.append(item)
return cart
Rewrite it as add_item_fixed(item, cart=None) so that every call which doesn't pass its own cart starts from a fresh, empty list instead of sharing state across calls. Use the standard None-sentinel pattern (check "if cart is None" and build a new list inside the function body). Show three calls in a row (add_item_fixed("apple"), add_item_fixed("banana"), add_item_fixed("cherry")) proving each one returns a list with only its own item.
None itself is still one shared default object across
every call, exactly like the broken version — but since
None is immutable, sharing it causes no problem at
all. The if cart is None: cart = [] line is what
actually creates a brand-new, empty list, freshly, on every single
call that needs one.
- A default argument value is built once, at
deftime — not fresh on every call. - A mutable default (list/dict/set) means every call sharing that default shares the exact same object and its mutations.
- The standard fix: default to
None, then build the real mutable value inside the function body when it's actuallyNone.
Go Deeper: is a mutable default ever intentional?
Rarely, and almost always as a deliberate caching/memoization
trick where a function is meant to accumulate shared state across
calls on purpose (an internal cache dict, for instance). Even
then, it's considered surprising enough that it's usually spelled
out in a comment, since the vast majority of code that writes
def f(x=[]) did not intend this behavior at all.
- Default argument values are created once, at function-definition time, and reused across calls that don't override them.
- A mutable default means every such call shares and mutates the exact same object — checkable directly with
id(). - The fix: default to
None, and build a fresh mutable object inside the function body when needed.
4. __slots__
- By default, every instance of a class gets its own
__dict__to hold its attributes — flexible, but with real memory overhead per instance. __slots__ = (...)tells Python to skip that per-instance__dict__entirely, storing only the named attributes in a fixed, compact layout.- The trade-off: no dynamic attribute assignment beyond what's listed in
__slots__, and no straightforward multiple inheritance with other slotted classes.
__dict__ overhead adds up fast — __slots__ is a real, measurable lever for that specific situation, not a micro-optimization.
Measured directly, on the same two-attribute class written both ways:
import sys
class PointRegular:
def __init__(self, x, y):
self.x = x
self.y = y
class PointSlotted:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
r = PointRegular(1, 2)
s = PointSlotted(1, 2)
print("PointRegular instance size:", sys.getsizeof(r))
print("PointRegular __dict__ size:", sys.getsizeof(r.__dict__))
print("PointRegular total (instance + dict):", sys.getsizeof(r) + sys.getsizeof(r.__dict__))
print("PointSlotted instance size:", sys.getsizeof(s))
PointRegular instance size: 48
PointRegular __dict__ size: 296
PointRegular total (instance + dict): 344
PointSlotted instance size: 48
Thought process: a fair comparison needs both classes to be otherwise identical (same attributes, same __init__) so __slots__ is the only variable — and the regular class's TRUE cost has to include its __dict__ separately, since sys.getsizeof() on the instance alone would understate it and make the comparison look smaller than it really is.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python script using only sys.getsizeof() that measures the memory difference between a regular class and a __slots__ class with identical attributes. Define PointRegular with __init__(self, x, y) storing self.x and self.y normally, and PointSlotted with __slots__ = ("x", "y") and the same __init__. Create one instance of each with the same values. Print PointRegular's instance size, its __dict__'s size, and the sum of both (the true total cost) — then print PointSlotted's instance size alone. Also show that assigning a new attribute (r.z = 99) works on PointRegular but raises AttributeError on PointSlotted.
Both instances report the same 48-byte header on their own —
the real difference is the __dict__ that
PointRegular needs on top to actually hold
x and y: 296 more bytes, for a total of
344. PointSlotted needs no separate dict at all; its
two attributes live directly in the fixed slot layout, so 48 bytes
is the whole story. That gap only grows with more attributes and
more instances — it's why __slots__ matters most
for classes instantiated many thousands of times, not a one-off
object.
The cost side of the trade-off, directly observed:
r.z = 99
print("Regular allows dynamic attr: r.z =", r.z)
try:
s.z = 99
except AttributeError as e:
print("Slotted raises AttributeError:", e)
Regular allows dynamic attr: r.z = 99
Slotted raises AttributeError: 'PointSlotted' object has no attribute 'z' and no __dict__ for setting new attributes
__slots__ raises a TypeError ("multiple bases have instance lay-out conflict"), since Python can't merge two different fixed layouts into one. Regular classes (with a __dict__) don't have this restriction, since their attributes aren't laid out at fixed offsets to begin with.
- Without
__slots__, every instance carries its own__dict__— flexible, but real memory overhead per instance. __slots__ = ("x", "y")removes that per-instance dict, storing only the named attributes — measurably smaller per instance.- The cost: no attribute beyond what's listed in
__slots__can be added dynamically, and multiple inheritance across slotted classes is restricted.
Go Deeper: when is __slots__ NOT worth it?
When a class is instantiated only a handful of times (a config
object, a singleton-style manager), the per-instance savings are
negligible against the whole program's memory, while the loss of
dynamic attributes and easy multiple inheritance is a real,
ongoing cost to work around. __slots__ earns its
keep specifically when instance count is large —
thousands to millions — which is exactly the profile of a
parsed-data row, a graph node, or a game-engine entity.
- Regular instances carry a per-instance
__dict__;__slots__removes it, storing only the named attributes. - Measured here: 344 bytes (instance + dict) for a regular two-attribute instance vs. 48 bytes slotted — a gap that scales with instance count.
- The cost: no dynamic attributes beyond
__slots__, and restricted multiple inheritance across slotted classes.
5. Memory profiling basics
sys.getsizeof(obj)reports one object's size in bytes — useful for a single value, but it doesn't include memory held by objects it references.tracemalloctracks every allocation across a whole block of code, reporting current and peak memory use — the right tool for "how much memory did this function actually use?"- Comparing two approaches honestly means measuring both with the same tool, not guessing which "should" be smaller.
tracemalloc.get_traced_memory() around each version turns it into a measured fact — exactly what this chapter's project automates.
tracemalloc?
tracemalloc is a standard-library module that tracks every memory allocation Python makes while it's active. tracemalloc.start() begins tracking, tracemalloc.get_traced_memory() returns (current, peak) bytes traced so far, and tracemalloc.stop() ends tracking. Unlike sys.getsizeof(), it captures the full cost of a block of code — every list, string, and dict it allocates along the way — not just one object's own size.
The clearest demonstration: building the same 100,000 squared numbers two ways, one materializing a full list and one as a lazy generator (Chapter 17):
import tracemalloc
def squares_list(n):
return [i * i for i in range(n)]
def squares_gen(n):
return (i * i for i in range(n))
tracemalloc.start()
result = squares_list(100_000)
current, peak = tracemalloc.get_traced_memory()
print(f"List version -- current: {current:,} bytes, peak: {peak:,} bytes")
tracemalloc.stop()
tracemalloc.start()
result = squares_gen(100_000)
current, peak = tracemalloc.get_traced_memory()
print(f"Generator version -- current: {current:,} bytes, peak: {peak:,} bytes")
total = sum(result)
tracemalloc.stop()
List version -- current: 4,000,448 bytes, peak: 4,000,448 bytes
Generator version -- current: 408 bytes, peak: 408 bytes
Thought process: a trustworthy comparison needs each version measured in its own isolated tracemalloc session (start/measure/stop), not one shared session where earlier allocations could bleed into the second measurement — and the generator's memory has to be read immediately after creation, before it's ever iterated, or the "lazy" claim would be measuring the wrong moment.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python script using the standard library tracemalloc module that measures and compares the memory cost, at the moment of creation, of a list comprehension vs. an equivalent generator expression. Write squares_list(n) returning [i*i for i in range(n)] and squares_gen(n) returning (i*i for i in range(n)). For each, start tracemalloc, call the function with n=100_000, immediately read current/peak memory with get_traced_memory(), print both formatted with thousands separators, then stop tracemalloc. Make sure the generator's memory is measured before it is ever iterated or summed.
That's roughly 10,000× less memory for the
generator at the moment it's created — because
squares_gen() hasn't computed a single value yet at
that point, only set up the machinery to compute them one at a
time later. The list version, by contrast, has already computed
and stored all 100,000 numbers before tracemalloc even
takes its measurement. This exact comparison is the subject of
Sub-topic 6.
For finding where memory is going, not just how much,
tracemalloc.take_snapshot() breaks it down by the
line that allocated it:
import tracemalloc
def build_data(n):
return [str(i) * 3 for i in range(n)]
tracemalloc.start()
data = build_data(50_000)
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")
for stat in top_stats[:1]:
print(stat)
current, peak = tracemalloc.get_traced_memory()
print("current:", current, "peak:", peak)
tracemalloc.stop()
snapshot_demo.py:5: size=3136 KiB, count=50003, average=64 B
current: 3212940 peak: 3213162
That single line (the list comprehension inside
build_data()) accounts for essentially all the traced
memory — 3,136 KiB across 50,003
individual allocations. This is exactly the kind of report
"top allocations" means in a real memory profiler: not a single
total number, but a ranked list of which lines are responsible for
how much.
sys.getsizeof(obj)measures one object's own size — fast, but doesn't follow references to what it contains.tracemalloc.start()/get_traced_memory()/stop()measures current and peak memory across a whole block of code.tracemalloc.take_snapshot().statistics("lineno")ranks memory use by the line that allocated it — the basis of "top allocations."
Go Deeper: does sys.getsizeof() include a list's contents?
No — sys.getsizeof([1, 2, 3]) reports only the
list object's own overhead (the array of pointers it holds), not
the size of the three integers it points to. Those integers exist
as separate objects with their own sizes (and in CPython, small
integers are often shared/cached across the whole program
anyway). This is exactly why tracemalloc, which
tracks every allocation as it happens rather than inspecting one
object after the fact, is the right tool for "how much memory did
this whole operation use," while sys.getsizeof()
answers the narrower "how big is this one object, on its own."
sys.getsizeof(obj)measures one object's own size, not what it references.tracemallocmeasures current/peak memory across a whole block of code — the right tool for comparing two approaches honestly.tracemalloc.take_snapshot().statistics("lineno")ranks allocations by source line, the basis of a real "top allocations" report.
6. Generators as the memory-efficient alternative
- Chapter 17 introduced generators as lazy, memory-efficient iterables — this sub-topic makes that claim concrete with a measured before/after.
- A list comprehension computes and stores every value upfront; a generator expression computes one value at a time, only when asked.
- The right choice depends on whether every value is genuinely needed in memory at once, or whether the data is only ever consumed one item at a time.
tracemalloc in hand, that design choice has a number behind it, not just an assertion.
Sub-topic 5's measurement, restated as the direct point of this whole chapter: a list comprehension over 100,000 items costs roughly 4 MB the moment it's built, since Python must store every single one of those 100,000 integers immediately. The equivalent generator expression costs 408 bytes at that same moment, because it hasn't produced a single value yet — it's only a small object holding instructions for producing values later, one at a time, on demand.
List version -- current: 4,000,448 bytes, peak: 4,000,448 bytes
Generator version -- current: 408 bytes, peak: 408 bytes
Thought process: the interesting decision here isn't "generators are better" — it's writing code that decides which one to use based on the actual access pattern (one-pass vs. needs-random-access), since that's the real judgment call a working developer has to make, not a fixed rule to apply blindly.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python function called should_use_generator(passes_needed, needs_random_access) using only the standard library. It should return True only when passes_needed equals 1 AND needs_random_access is False — the specific case where a generator's memory savings apply without losing anything the caller actually needs. Return False in every other case (multiple passes needed, or random/indexed access needed). Include three example calls showing a True case, a False case from passes_needed > 1, and a False case from needs_random_access being True.
This isn't a free lunch, though — it's a genuine trade-off, and choosing correctly means being honest about which side of it a given task actually needs:
- A generator can only be consumed once, in order — once exhausted, there's nothing left to iterate again, unlike a list.
- A generator has no
len(), no indexing (gen[3]fails), and no way to know how many items remain without consuming them. - If code needs to loop over the data multiple times, sort it, or look something up by index, a real list is still the right choice — the memory savings only apply to genuinely one-pass, in-order processing.
That's exactly the shape of Chapter 17's log analyzer: read a potentially huge file, process each line once, in order, and never need to go back — the ideal case for a generator, and the reason a genuinely huge log file could be processed at all without loading the whole thing into memory first.
tracemalloc's "peak" is the highest memory use reached at any point while tracking was active, even if it later dropped back down. For the list comprehension, current and peak are identical here because nothing was freed during the measurement window. In a longer-running function that builds and then discards several temporary structures, peak can be meaningfully higher than the final "current" figure — which is often the more important number, since it represents the worst-case memory the program actually needed at once.
- Generators trade "all values available anytime, any order" for "vastly less memory, one value at a time, forward-only."
- The measured gap (roughly 10,000× here) grows with the size of the data — the bigger the dataset, the more a generator's lazy approach matters.
- Choose a generator when data is processed once, in order; choose a list when random access, repeated iteration, or built-in list methods are genuinely needed.
Go Deeper: what about a generator that's converted to a list right away?
list(some_generator()) gives back all the memory
savings immediately, since it forces every value to be computed
and stored at once — at that point it costs exactly what
the equivalent list comprehension would have cost from the
start. The savings only exist while the data stays in generator
form, consumed lazily; converting it to a list early defeats the
entire purpose.
- A list comprehension computes and stores every value immediately; a generator expression computes one value at a time, on demand.
- Measured here: ~4 MB for a 100,000-item list vs. 408 bytes for the equivalent generator, at the moment of creation.
- Generators are forward-only and single-use — the right tool specifically for one-pass, in-order processing of data too large (or wasteful) to hold entirely in memory.
- Long-running services (web servers, background workers) live or die by avoiding reference cycles and unbounded memory growth — a "memory leak" in Python is almost always an unintentionally-retained reference, not literally leaked memory the OS can't reclaim.
__slots__is a standard optimization in performance-sensitive libraries that create huge numbers of small objects — ORMs, parsers, and data-processing pipelines all use it deliberately.- Profiling with
tracemallocbefore optimizing anything is standard professional practice — guessing which part of a program uses the most memory is reliably wrong often enough that measuring first is the only trustworthy approach.
Points to Remember
- Every Python object tracks a reference count; it's freed the instant that count reaches zero.
sys.getrefcount()reports it, always one higher than expected since the call itself adds a temporary reference. - A reference cycle keeps objects' refcounts above zero even when nothing else can reach them; the cyclic garbage collector (
gcmodule) finds and frees these cycles, automatically and viagc.collect(). - The mutable default argument gotcha is a direct consequence of the object model: default values are built once, at
deftime, and a mutable default is shared and mutated across every call that doesn't override it. Fix with aNonesentinel. __slots__removes a class instance's per-instance__dict__, saving real, measurable memory per instance, at the cost of dynamic attributes and easy multiple inheritance with other slotted classes.sys.getsizeof()measures one object;tracemallocmeasures a whole block of code's current/peak memory, andtake_snapshot().statistics("lineno")ranks allocations by source line.- Chapter 17's generators are the concrete, measured memory-efficient alternative to materializing a full list — vastly less memory for one-pass, in-order processing, at the cost of single-use, forward-only iteration.