Interview Q&A · Python · 35 questions in this topic

Advanced Python — Python Interview Q&A

All Python topics

The internals interviewers probe on senior rounds — memory model, the GIL, slots, profiling, descriptors and the corners of the language standard guides skip. Part of Advanced Python · 375 questions in the Python bank.

How does Python manage memory, in more depth than the basics?

Answer

CPython uses reference counting as its primary memory management mechanism, backed by a generational cyclic garbage collector for reference cycles, and an internal memory allocator (pymalloc) that manages small-object memory in efficient pools rather than calling the operating system's allocator for every single object.

pymalloc exists because general-purpose OS memory allocation is relatively expensive, and Python programs typically create huge numbers of small, short-lived objects — a specialized allocator that manages pre-allocated pools of fixed-size memory blocks is dramatically faster for this specific workload pattern.

Example

Example.pypython
import sys
x = []
print(sys.getrefcount(x)) # baseline refcount (includes the temporary arg reference)
y = x
print(sys.getrefcount(x)) # incremented -- another name references the same object
del y
print(sys.getrefcount(x)) # decremented again

💡 Structuring the answer in three layers — reference counting (immediate, deterministic), cyclic GC (handles what refcounting can't), and pymalloc (performance optimization for small objects) — shows a complete mental model rather than just "Python has garbage collection."

What is reference counting, and how can you inspect an object's reference count?

Answer

Every object keeps a count of how many references point to it. When that count drops to zero, CPython deallocates the object immediately and deterministically. You can inspect it with sys.getrefcount(obj), though the returned value is always at least one higher than you'd naively expect.

sys.getrefcount() 's result includes the temporary reference created by passing the object into getrefcount() itself as an argument — so a "genuinely unreferenced" object still reports a count of 1, not 0, when checked this way.

Example

Example.pypython
import sys
a = [1, 2, 3]
print(sys.getrefcount(a)) # e.g. 2 -- 'a' itself, plus the temporary arg to
getrefcount()
b = a
print(sys.getrefcount(a)) # e.g. 3 -- 'a', 'b', plus the temporary arg
del b
print(sys.getrefcount(a)) # back to e.g. 2

💡 Mentioning that getrefcount() 's result is always inflated by one (due to its own argumentpassing) is a small correctness detail that shows you've actually used the function, not just read about it.

What causes reference cycles, and how does Python's cyclic garbage collector handle them?

Answer

A reference cycle occurs when two or more objects reference each other (directly or through a longer chain), so their reference counts never naturally reach zero even after nothing outside the cycle refers to them. Python's separate cyclic garbage collector periodically scans for and collects these otherwise-unreachable cycles.

The cyclic collector works by tracking "container" objects (those that can hold references to other objects, like lists, dicts, and class instances) and periodically checking whether groups of them are only reachable from within the group itself — such groups are true garbage, even though no individual object's reference count is technically zero.

Example

Example.pypython
import gc
class Node:
    def __init__(self, name):
        self.name = name
        self.partner = None
a = Node("A")
b = Node("B")
a.partner = b # a references b
b.partner = a # b references a -- a cycle!
del a, b # neither object's refcount reaches zero -- they still reference each other
collected = gc.collect() # manually trigger the cyclic collector
print(f"Cyclic garbage collected: {collected} objects")

💡 A concrete example of why cycles happen in real code — parent/child object relationships, doubly linked lists, observer patterns with back-references — makes this answer much more convincing than the abstract a.partner = b demonstration alone.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits