Interview Questions: Memory Management in Python
Memory management questions separate candidates who've memorized syntax from candidates who understand what's actually happening underneath. This set covers reference counting, reference cycles and the garbage collector, the mutable default argument gotcha, __slots__, and memory profiling.
1 How does Python decide when to free an object's memory?
Every object carries a reference count — how many references currently point to it. Creating a reference (assignment, passing an argument, appending to a container) increments it; removing one (del, reassignment, going out of scope) decrements it. The instant that count reaches zero, CPython frees the object immediately — there's no separate "sweep" pass for this common case. A backup cyclic garbage collector handles the one case reference counting can't: objects that reference each other in a cycle.
Red flagsSaying Python "just garbage collects everything" without distinguishing reference counting (the default, always-on mechanism) from the separate cyclic collector (a backup for a specific case).
Follow-up"Is memory freed immediately, or does the program have to wait?" (Immediately, for the reference-counting case — the moment the count hits zero. Reclaiming a reference cycle waits until the cyclic collector actually runs, which is periodic, not instant.)
2 Why does sys.getrefcount(x) report a number one higher than expected?
Calling getrefcount(x) passes x as an argument to the function, which itself creates one temporary reference to x for the duration of the call. So the reported count always includes that extra, temporary reference on top of whatever "real" references exist in the surrounding code.
Red flagsAssuming the number is a bug or being unable to explain the off-by-one at all.
Follow-up"If a = [1,2,3] and nothing else references it, what does getrefcount(a) return?" (2 — one for a itself, one temporary reference from the getrefcount() call.)
3 What's a reference cycle, and why is it a genuine problem for reference counting?
A reference cycle is two or more objects that reference each other, directly or through a chain — for example, two nodes each storing the other as a .partner attribute. Even when nothing outside that pair can reach either node anymore, each node still holds a reference to the other, so neither one's refcount ever drops to zero on its own. Reference counting alone would leave both objects in memory forever.
Red flagsClaiming Python "can't handle" cycles at all, missing that the separate cyclic garbage collector exists specifically to solve this.
Follow-up"Give a real-world example of a reference cycle." (A parent object holding a list of children, where each child also stores a reference back to its parent — a very common, easy-to-write-by-accident pattern in tree/graph structures and GUI widget hierarchies.)
4 How does the cyclic garbage collector actually find and free a reference cycle?
The gc module periodically scans tracked objects (container types like lists, dicts, and class instances, which are the only kinds that can participate in a cycle) looking for groups that are unreachable from anything outside the group, even though their internal reference counts are still above zero. When it finds such a group, it breaks the cycle and frees every object in it together. This can be triggered manually with gc.collect(), or happens automatically once a generation's allocation count crosses a threshold (gc.get_threshold()).
Red flagsDescribing garbage collection as though it replaces reference counting entirely, rather than working alongside it as a backup for the cyclic case specifically.
Follow-up"What are the three generations in gc.get_count(), and why do they exist?" (Objects are grouped by how long they've survived — new objects start in generation 0, and surviving a collection promotes them to the next generation. Younger generations are collected far more often, since most objects — and most cycles — die young, making that the most efficient place to check first.)
5 Walk through exactly why def f(x=[]) is a bug waiting to happen.
The default value [] is evaluated exactly once — when the def statement itself runs, not each time f() is called. That single list object is stored as the parameter's default and reused, by reference, on every call that doesn't supply its own x. Since lists are mutable, any call that appends to x actually mutates that one shared object, so its state silently persists and accumulates across unrelated calls. This isn't special mutable-argument behavior — it's the same object/reference model that governs every assignment in Python, just applied to a spot (a default value) where the "created once" part is easy to overlook.
Red flagsDescribing this as an arbitrary Python quirk or gotcha to just memorize, rather than a predictable consequence of default values being created once at definition time.
Follow-up"Would the same problem happen with a default of 0 or an empty string?" (No — integers and strings are immutable, so even though the same default object is still reused every call, there's no way to mutate it in place. The bug only shows up with mutable defaults: lists, dicts, sets, or mutable custom objects.)
6 What's the standard fix for the mutable default argument problem, and why does it work?
Default the parameter to None instead, then check "if x is None: x = []" as the first line inside the function body. None is still one shared default object reused across every call, exactly like the broken version — but since None is immutable, sharing it causes no problem. The "if x is None" check then builds a genuinely new, empty list fresh, inside the function body, every single time the function actually needs one.
Red flagsSuggesting a "fix" that still shares a mutable object, or not understanding why None specifically is safe to share.
Follow-up"Could you check `if not x` instead of `if x is None`?" (Not safely — `if not x` is also True for an empty list passed in on purpose, silently replacing a caller's genuinely empty list with a new one. `is None` checks specifically for "no argument was given," which is the actual condition that matters.)
7 What does __slots__ actually do, mechanically?
By default, every class instance gets its own __dict__ to hold whatever attributes get assigned to it — flexible, but with real per-instance memory overhead for that dict. Declaring __slots__ = ("x", "y") tells Python to skip creating that per-instance __dict__ entirely, instead reserving a small, fixed-size slot for exactly the named attributes. Measured directly on a simple two-attribute class, a slotted instance can end up well under half the size of a regular instance plus its dict.
Red flagsDescribing __slots__ as "just a performance flag" without being able to explain the __dict__ mechanism it's actually changing.
Follow-up"When does __slots__ actually matter in practice?" (When a class is instantiated a very large number of times — thousands to millions — like parsed data rows, graph nodes, or game-engine entities. For a class instantiated a handful of times, the savings are negligible against the cost of losing dynamic attributes.)
8 What are the real costs of using __slots__?
Two concrete costs: first, no attribute beyond what's explicitly listed in __slots__ can be assigned dynamically — trying raises an AttributeError, since there's no __dict__ left to catch it. Second, inheriting from two different slotted classes that each define their own non-empty __slots__ raises a TypeError, because Python can't merge two different fixed memory layouts into one — a real restriction on multiple inheritance that regular (dict-based) classes don't have.
Red flagsPresenting __slots__ as a strictly-better default with no downsides — it's a deliberate trade-off, not a free optimization.
Follow-up"Can a slotted class still support one additional dynamic attribute if needed?" (Yes — adding "__dict__" itself as one of the names in __slots__ restores a (now optional) per-instance dict, though that gives back most of the memory savings the slots were meant to provide in the first place.)
9 What's the difference between sys.getsizeof() and tracemalloc?
sys.getsizeof(obj) reports one object's own size, in isolation — it does not follow references to whatever that object contains or points to. tracemalloc tracks every memory allocation Python makes while it's running, over a whole block of code, reporting current and peak totals across everything allocated in that window — the right tool for "how much memory did this function actually use," not just "how big is this one value."
Red flagsUsing sys.getsizeof() on a list and assuming it includes the size of everything the list contains — it doesn't.
Follow-up"How would you find out which specific line of code is responsible for the most memory?" (tracemalloc.take_snapshot().statistics("lineno") — ranks every tracked allocation by the source line that made it, exactly what a real memory profiler's "top allocations" report shows.)
10 Why does a generator expression use so much less memory than an equivalent list comprehension?
A list comprehension computes and stores every resulting value immediately — for 100,000 items, that means 100,000 actual objects sitting in memory before anything else happens. A generator expression, by contrast, doesn't compute anything up front — it's a small object holding only the instructions for producing values later, one at a time, only when something actually asks for the next one. Measured directly, a 100,000-item list comprehension costs roughly 4 MB at creation, while the equivalent generator costs a few hundred bytes — because nothing has been computed yet.
Red flagsClaiming generators are "always better" without acknowledging they trade away random access and repeated iteration to get that memory savings.
Follow-up"If you then do list(some_generator()), does the memory savings still apply?" (No — converting to a list forces every value to be computed and stored at once, costing exactly what the list comprehension would have cost from the start. The savings only exist while the data is consumed lazily, in generator form.)
11 What real limitations does a generator have compared to a list?
A generator can only be consumed once, moving forward — once every value has been produced, there's nothing left to iterate again, unlike a list which can be looped over repeatedly. It also has no len(), no indexing (gen[3] fails), and no way to know how many items remain without consuming them to find out. These aren't bugs — they're the direct cost of never actually holding all the values in memory at once.
Red flagsNot recognizing that a generator is single-use, and being surprised that iterating it twice produces nothing the second time.
Follow-up"When would a list clearly be the better choice over a generator, even with a big dataset?" (When the data needs to be sorted, indexed into, iterated more than once, or passed to something requiring len() — any of these needs a real list, and the memory savings of a generator only pay off for genuinely one-pass, in-order processing.)
12 How would you actually determine whether an optimization (like switching to a generator, or adding __slots__) helped, rather than just assuming it did?
Measure both versions with the same tool, under the same conditions, rather than reasoning about which "should" be smaller. tracemalloc.start()/get_traced_memory()/stop() around each version gives real current/peak byte counts to compare directly. For a single object's size specifically (like comparing a regular vs. a slotted instance), sys.getsizeof() on each gives a direct, comparable number. Guessing which approach uses less memory is reliably wrong often enough that measuring first is the only trustworthy approach.
Red flagsAnswering with confidence about which approach "obviously" uses less memory without mentioning measuring it directly.
Follow-up"Why might exact byte counts differ between two runs of the identical code?" (Python version, platform (32-bit vs 64-bit builds have different pointer sizes), and even what ran immediately before in the same process can all shift small allocation details — which is exactly why comparisons should focus on relative differences, not memorizing one exact number as universal.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.