Autocoder

Python Memory Management Interview Questions

Last updated 2026-11-19

Memory management questions are common in interviews for experienced Python roles, and increasingly in fresher rounds that want to see how well you understand objects and references. The questions test whether you can explain what happens between creating an object and its memory being reclaimed.

This page covers reference counting, the cyclic garbage collector, interning and small-integer caching, copy semantics, weak references, __slots__ and the usual causes of memory leaks in long-running Python programs. All descriptions refer to CPython.

Level2 to 5 years, also fresher
FocusCPython object model and garbage collection
VersionCPython 3.10 and later

Key vocabulary

Use the right terms: reference count, cyclic garbage collector, generation, private heap, pymalloc arena. Mention that these are CPython details and not guaranteed by the language, which shows maturity.

Related topics

References and copies also appear on the main Python page, and threads and the GIL are covered in multithreading and multiprocessing. General preparation steps are in how to crack a Python interview.

Python Memory Management Interview Questions: questions with worked answers

  1. 1

    How is memory managed in Python?

    easy

    CPython keeps all objects in a private heap that the interpreter manages, so the programmer never calls malloc or free. Memory is reclaimed in two ways: reference counting, which frees an object as soon as its count reaches zero, and a generational cyclic garbage collector that finds groups of objects referencing each other but unreachable from the program. Small objects are served from pymalloc, an arena-based allocator that cuts allocation overhead.

  2. 2

    What is reference counting? How can you inspect it?

    medium

    Every object stores a count of references to it. Binding a name, adding to a container or passing as an argument increments it, and deleting a name or leaving a scope decrements it. At zero the object is deallocated immediately and its __del__ runs. sys.getrefcount(x) returns the count, which is one higher than expected because the argument itself is a temporary reference.

    python
    import sys
    a = []
    print(sys.getrefcount(a))   # 2
    b = a
    print(sys.getrefcount(a))   # 3
    del b
    print(sys.getrefcount(a))   # 2
  3. 3

    Why is a garbage collector needed if reference counting exists?

    medium

    Reference counting cannot free cycles. If two objects reference each other, their counts never reach zero even after the program loses all other references. The cyclic collector, exposed through the gc module, periodically scans container objects, finds unreachable cycles and frees them. It uses three generations: new objects are checked often, and survivors move to older generations that are checked less often.

    python
    import gc
    class Node:
        def __init__(self): self.other = None
    a, b = Node(), Node()
    a.other, b.other = b, a
    del a, b
    print(gc.collect() >= 2)   # True: the cycle was found
  4. 4

    What are generations in Python's garbage collector?

    medium

    Objects start in generation 0. When allocations minus deallocations exceed a threshold, generation 0 is collected, and survivors are promoted to generation 1, then 2. The idea is that most objects die young, so collecting young objects often is cheap. gc.get_threshold() shows the limits and gc.set_threshold can tune them, though changing them is rarely needed. gc.disable() turns off only the cycle collector, not reference counting.

  5. 5

    What is the output of this reference cycle with __del__, and what changed in Python 3.4?

    hard

    Before Python 3.4, objects in a cycle that defined __del__ could not be collected and ended up in gc.garbage. Since PEP 442 the collector can finalise them, so such cycles are freed normally. It is still advisable to avoid __del__ because the call time is not guaranteed, and to use context managers or weakref.finalize for cleanup.

  6. 6

    What are small integer caching and string interning?

    medium

    CPython preallocates integer objects from -5 to 256 and reuses them, so two names bound to such a value refer to the same object. Some strings, notably identifier-like literals, are interned so equal literals share one object, which speeds up dictionary lookups. This is an optimisation, not a rule, and is why a is b can surprise you. Compare values with ==.

    python
    a, b = 256, 256
    print(a is b)       # True
    x = int("1000"); y = int("1000")
    print(x == y, x is y)   # True False
    import sys
    print(sys.intern("hello world") is sys.intern("hello world"))  # True
  7. 7

    Does del x delete the object?

    medium

    No. del x removes the name x and decrements the object's reference count. The object is destroyed only if that was the last reference. del lst[i] or del d[k] removes an entry from a container, which also decrements the count of the removed object.

    python
    a = [1, 2, 3]
    b = a
    del a
    print(b)      # [1, 2, 3]  -- the list still exists
  8. 8

    What is a weak reference and when would you use it?

    medium

    A weak reference, from the weakref module, refers to an object without increasing its reference count, so it does not keep the object alive. When the object dies, the weak reference returns None. Typical uses are caches and observer lists that must not prevent cleanup, for example WeakValueDictionary. Built-in lists, dicts and ints cannot be weakly referenced, but user-defined class instances can.

    python
    import weakref
    class Obj: pass
    o = Obj()
    r = weakref.ref(o)
    print(r() is o)    # True
    del o
    print(r())         # None
  9. 9

    How can a Python program leak memory?

    medium

    Common causes are unbounded caches or global dictionaries that keep growing, lists that accumulate results never cleared, reference cycles involving objects with expensive resources, closures or callbacks that hold large objects, and listeners never unregistered. Fixes include bounding caches with lru_cache(maxsize=...), using weak references, clearing collections and using context managers. Diagnose with tracemalloc, which shows where allocations came from.

    python
    import tracemalloc
    tracemalloc.start()
    data = [bytes(1000) for _ in range(1000)]
    snap = tracemalloc.take_snapshot()
    print(snap.statistics("lineno")[0].size > 900_000)   # True
  10. 10

    What does __slots__ change about memory use?

    medium

    Each normal instance carries a __dict__ to store attributes, which costs significant memory for millions of small objects. With __slots__ the attributes are stored in a compact fixed structure and there is no instance dict. The trade-offs are that you cannot add arbitrary attributes, and inheritance and weak references need extra care.

    python
    class P:
        __slots__ = ("x", "y")
        def __init__(self, x, y): self.x, self.y = x, y
    p = P(1, 2)
    print(hasattr(p, "__dict__"))   # False
    p.z = 3                         # AttributeError
  11. 11

    How does Python allocate memory for lists, and what is over-allocation?

    hard

    A list stores an array of pointers. When it grows past its capacity, CPython allocates a bigger array, roughly one eighth larger plus a constant, and copies the pointers. This over-allocation makes append O(1) amortised. getsizeof shows the container's size including spare capacity but not the objects it points to, so the real footprint is larger.

    python
    import sys
    a = []
    sizes = set()
    for i in range(30):
        a.append(i)
        sizes.add(sys.getsizeof(a))
    print(len(sizes) < 30)   # True: capacity jumps in steps
  12. 12

    What is the difference between shallow and deep copy in terms of memory?

    medium

    A shallow copy allocates a new container and copies the references, so both containers point to the same inner objects and extra memory is small. A deep copy allocates new objects for everything reachable, so memory and time double for the copied structure. Choose a shallow copy when inner items are immutable or should be shared. See the Python interview questions page for the nested list example.

  13. 13

    Does Python return freed memory to the operating system?

    hard

    Not always. CPython frees objects back to its own allocators, and pymalloc arenas are released to the OS only when completely empty, so fragmentation can keep a process's resident size high after you delete data. Large objects allocated directly by the system allocator are usually returned. For truly long-running jobs, processing in a short-lived subprocess is a reliable way to reclaim memory.

Frequently asked questions

Does Python have manual memory management?

No. The interpreter allocates and frees memory. You can influence it with del, the gc module and weak references, but you do not free memory directly.

What does gc.collect() do?

It forces a full collection of the cyclic garbage collector across all generations and returns the number of unreachable objects found. It does not affect objects freed by reference counting.

Are other Python implementations the same?

No. PyPy uses a tracing garbage collector and has no reference counting, so objects may live longer and __del__ timing differs. Always describe CPython when you answer.

How do I measure an object's size?

sys.getsizeof gives the shallow size in bytes. For nested structures, sum recursively or use tracemalloc or third-party tools.

Related guides

More in Programming Language Interview Questions by Language

See all in this section