Advertisement

Memory Management & Garbage Collection interview questions and answers

15 Memory Management & Garbage Collection interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How can generators and iterators help reduce peak memory usage compared to building full lists?

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 & Generators Iterators & the Iterator Protocol
Q12 Intermediate Save

How do mutable default arguments create a subtle memory and correctness pitfall related to object lifetime?

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?
  • What's the standard fix using None as sentinel?
Functions & Scope Debugging & Profiling
Q13 Advanced Save

What is memory fragmentation in the context of Python's object allocator, and how does pymalloc address it for small objects?

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?
  • Why do large objects bypass pymalloc?
Debugging & Profiling Data Types & Structures
Q14 Intermediate Save

How does the tracemalloc module help track where memory is being allocated in a running program?

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?
Debugging & Profiling Logging
Q15 Advanced Save

How do circular references between objects with __del__ methods behave differently in Python 3.4+ compared to earlier versions?

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.
Likely follow-ups
  • What was PEP 442 and what problem did it solve?
  • Why is relying on __del__ order still risky?
Multiple Inheritance & MRO Debugging & Profiling

Showing 11–15 of 15