Guide Python Intermediate

5.12 Memory Representation

How Python stores objects on the heap, why a variable is a reference rather than a box holding a value, and how CPython's reference-counting garbage collector works.

2 min read

How Python Stores Objects

Every Python object lives on the heap and carries metadata beyond its raw value — a reference count and a type pointer at minimum (the full breakdown, specific to strings, is in 9.1 Introduction to Strings).

References

What Is It?

A variable name is not a box holding a value — it’s a label pointing at an object elsewhere in memory.

Why Does It Matter?

Assigning b = a doesn’t copy a’s data; both names end up pointing at the exact same object.

flowchart LR A["a = [1, 2, 3]"] --> OBJ["[1, 2, 3]\nid: 0x7f... refcnt=2"] B["b = a"] --> OBJ

Two names referencing one shared object.

>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> a               # mutation via b is visible through a too
[1, 2, 3, 4]
>>> id(a) == id(b)
True

Garbage Collection Overview

What Is It?

CPython automatically frees an object’s memory once nothing references it anymore, primarily via reference counting (each object tracks how many references point to it; it’s freed when that count hits zero), with a supplementary cyclic garbage collector for reference cycles that counting alone can’t catch.

>>> import sys
>>> x = [1, 2, 3]
>>> sys.getrefcount(x)    # includes the temporary reference getrefcount's own argument creates
2

Quick Interview Answer

“A Python variable is a reference, not a box — b = a makes both names point at the same object rather than copying it, so mutating through one name is visible through the other. CPython frees memory primarily via reference counting: each object tracks how many references point to it and is freed at zero, with a supplementary cyclic garbage collector catching reference cycles that counting alone can’t.”

Common Mistakes

  • Assuming b = a copies a list or dict — it doesn’t; both names reference the same object, so mutating one affects the other.
  • Forgetting reference cycles exist (e.g. two objects referencing each other) — plain reference counting alone can’t free them, which is why CPython also runs a cyclic collector.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form