🐍 Python for Everyone

← Back to all chapters

Chapter 25 of 33 Intermediate 70 min read

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

Chapter 10 mentioned that Python cleans up objects "automatically" and moved on. This chapter opens that up: automatically how, exactly — and what happens in the one case where "automatically" quietly fails unless something else steps in.
Sub-topic 1 of 6

1. How Python manages memory & reference counting

At a glance
  • 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.
Why this matters: "when does Python free memory?" has a precise, mechanical answer — not "eventually" or "when it feels like it." Reference counting is that answer for the vast majority of objects in any Python program.
What is... reference counting? Every Python object carries a hidden counter tracking how many references point to it. Creating a reference (assignment, a function argument, appending to a container) increments it; removing a reference (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:

refcount_demo.py
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))
actual output of refcount_demo.py (Python 3.14.4)
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.

What is... __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.
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.

Quick recap
  • 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.
Sub-topic 2 of 6

2. Reference cycles & the garbage collector

At a glance
  • 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 gc module) 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.
Why this matters: without a backup mechanism, a genuinely unreachable cluster of objects (two nodes pointing at each other, a parent-child pair, a callback holding a reference back to its owner) would sit in memory forever — reference counting alone would never notice it should be freed.

Before the code: here's the exact shape of the problem, two objects holding a reference to each other:

a two-object reference cycle
  +----------+          +----------+
  |  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:

cycle_demo.py
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()
actual output of cycle_demo.py
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.

What is... a "generation" in 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.
gc_get_count.py
import gc

print("gc.get_count() right now:", gc.get_count())
print("gc.get_threshold():", gc.get_threshold())
actual output of gc_get_count.py (values vary run to run)
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.

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.

Quick recap
  • 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 (gc module) 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.
Sub-topic 3 of 6

3. The mutable default argument gotcha

At a glance
  • 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.
Why this matters: this is one of the most common real Python bugs, and one of the most common interview questions — and it looks like a mystery until you already know that "the same object, reused" is exactly what def creates once at definition time.

Here's the broken version, run three times in a row:

mutable_default_broken.py
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"))
actual output of mutable_default_broken.py
['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:

id_check.py
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]))
actual output of id_check.py -- identical id() both times
id check -- same default object reused every call:
128675401047424
128675401047424
What is... __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:

mutable_default_fixed.py
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"))
actual output of mutable_default_fixed.py
['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.

try_it.py
Click "Run Code" — try switching back to the broken cart=[] version to see the difference.
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.

Quick recap
  • 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.
Sub-topic 4 of 6

4. __slots__

At a glance
  • 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.
Why this matters: when a program creates a very large number of small objects (rows of parsed data, nodes in a big structure), the per-instance __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:

slots_demo.py
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))
actual output of slots_demo.py (Python 3.14.4 -- exact numbers vary by version)
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:

slots_tradeoff.py
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)
actual output of slots_tradeoff.py
Regular allows dynamic attr: r.z = 99
Slotted raises AttributeError: 'PointSlotted' object has no attribute 'z' and no __dict__ for setting new attributes
What is... the multiple-inheritance limitation? Each slotted class reserves a fixed-size memory layout for its own listed attributes. Trying to inherit from two slotted classes that each define their own non-empty __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.
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.

Quick recap
  • 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.
Sub-topic 5 of 6

5. Memory profiling basics

At a glance
  • 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.
  • tracemalloc tracks 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.
Why this matters: "this version probably uses less memory" is a guess; tracemalloc.get_traced_memory() around each version turns it into a measured fact — exactly what this chapter's project automates.
What is... 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):

tracemalloc_demo.py
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()
actual output of tracemalloc_demo.py
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:

snapshot_demo.py
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()
actual output of snapshot_demo.py (line number will differ if you copy this)
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.

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."

Quick recap
  • sys.getsizeof(obj) measures one object's own size, not what it references.
  • tracemalloc measures 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.
Sub-topic 6 of 6

6. Generators as the memory-efficient alternative

At a glance
  • 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.
Why this matters: Chapter 17's Large-File Streaming Log Analyzer project worked specifically because it never materialized the whole file as a list — now, with 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 vs. generator, at the moment of creation (from Sub-topic 5)
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:

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.

What is... "peak" memory, specifically? 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.
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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →