Python · The language, not just syntax

How does Python manage memory and how do you reduce usage?

Hardmemoryreference countingslotsUpdated Oct 2026
Quiz this track

Short answer

CPython frees objects primarily by reference counting and uses a generational collector for cycles. Small objects are allocated from arenas managed by pymalloc, and __slots__ can remove the per-instance dict.

Every object has a reference count. When a name is bound, passed or stored, the count increases; when a reference goes away, it decreases. At zero the object is freed immediately, which gives deterministic cleanup for most objects.

python
import sys

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

point = Point(1, 2)
print(sys.getsizeof(point))
print(sys.getsizeof(point.__class__.__dict__))
slots removes the instance __dict__, cutting memory per object. It also prevents adding arbitrary attributes.

Where memory goes

  • Reference counting handles most frees immediately
  • The cyclic collector handles reference cycles that counting cannot break
  • pymalloc serves small objects from arenas to reduce allocator overhead
  • Large containers and copies dominate real-world memory, not small integer interning

Lists and dicts over-allocate to make appends cheap, so peak memory can exceed the logical size. Loading a whole file or query result into memory is a common cause of growth. Stream with generators, process in chunks, and release references to large objects promptly.

del removes a name binding; it does not necessarily free the object if other references exist. Caches and global registries are frequent hidden retainers, so use bounded caches and weak references.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between reference counting and tracing GC?
  2. 2Why does __slots__ reduce memory?
  3. 3How would you find a memory leak in a long-running service?
  4. 4Does del always free memory immediately?

Say it in the interview

CPython frees most objects immediately through reference counting and uses a generational collector for cycles. Small allocations come from pymalloc arenas. When memory matters I use __slots__, stream instead of materialising large collections, and bound caches. I watch for global registries and closures that keep objects alive, and I use tracemalloc or a profiler to confirm where allocations actually come from.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.