Generators produce values lazily, one at a time, without materializing the entire sequence in memory -- so processing a huge dataset with a generator pipeline can use constant memory (O(1)) instead of memory proportional to the dataset size (O(n)) that a list-based approach would require.
# Memory-heavy: builds a full list of a million squares
squares = [x**2 for x in range(1_000_000)]
# Memory-efficient: generator computes one at a time
squares_gen = (x**2 for x in range(1_000_000))
total = sum(squares_gen) # never holds all values at once
Real-world example
A CSV-processing script switches from reading all rows into a list to iterating with a generator expression, cutting peak memory usage from gigabytes to megabytes for very large files.
Likely follow-ups
When does a list still outperform a generator despite using more memory?
How does itertools.islice help limit generator consumption?
Comprehensions & GeneratorsIterators & the Iterator Protocol
A mutable default argument (like a list or dict) is created once when the function is defined, not each time it's called -- so all calls that don't override the argument share and mutate the same object, causing unexpected state to persist and accumulate across calls, which is both a correctness bug and an unintended long-lived memory reference.
def append_item(item, target=[]): # BUG: default list created once
target.append(item)
return target
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] -- unexpected! Same list reused
Real-world example
A web request handler using a mutable default dict parameter for 'options' accidentally leaks state between unrelated requests, causing one user's settings to bleed into another's response.
Likely follow-ups
Why does Python evaluate default arguments only once?
CPython's pymalloc allocator manages small objects (under 512 bytes) using pools and arenas sized to reduce fragmentation and avoid frequent calls to the OS allocator (malloc), which is comparatively slow and fragmentation-prone for many small, short-lived allocations typical of Python programs. Large objects bypass pymalloc and go directly to the system allocator.
import sys
# pymalloc handles allocation for small objects like this transparently
small_objects = [object() for _ in range(10000)] # efficiently pooled
# Large arrays typically go through the system allocator instead
import array
big = array.array('d', [0.0] * 10_000_000)
Real-world example
Profiling a Python application's memory allocator behavior with tools like tracemalloc reveals many small, short-lived dict and tuple allocations that pymalloc handles efficiently versus the pattern for very large NumPy arrays which bypass it.
Likely follow-ups
How does tracemalloc help profile allocation patterns?
tracemalloc records the Python call stack at the time of each memory allocation, letting you take snapshots and compare them to find exactly which lines of code are responsible for the largest or newest memory allocations -- invaluable for diagnosing memory leaks or unexpectedly high memory usage in long-running applications.
import tracemalloc
tracemalloc.start()
# ... run some code ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:3]:
print(stat)
Real-world example
A web server experiencing gradual memory growth uses tracemalloc to take snapshots an hour apart and diff them, pinpointing a specific caching function that never evicts old entries.
Likely follow-ups
How do you compare two snapshots to find leaks with compare_to?
What's the performance overhead of running tracemalloc in production?
Before Python 3.4 (PEP 442), objects in a reference cycle where any participant defined __del__ could never be automatically collected -- they were placed in gc.garbage and effectively leaked forever, requiring manual intervention. Since PEP 442, the garbage collector can safely finalize objects in cycles even with __del__ methods present, calling each object's __del__ exactly once and correctly handling resurrection edge cases, though relying on __del__ for critical logic is still discouraged.
import gc
class Node:
def __del__(self):
print('Node destroyed')
a, b = Node(), Node()
a.ref, b.ref = b, a # cycle
del a, b
gc.collect() # in 3.4+, both __del__ methods run correctly during collection
Real-world example
A legacy codebase migrating from Python 2 removes workarounds that manually broke reference cycles before deletion, since Python 3.4+'s collector safely handles cycles involving __del__ without that extra code.