Stop 14 · Advanced PythonTopics · 1/8

How Python Manages Memory

Part of the Python Roadmap

In short

Why did changing one list also change another? Why does a long-running script slowly eat RAM? Both answers come from how Python stores objects and decides when to throw them away.

In Python every value is an object and variables are references to it. CPython frees objects mainly through reference counting, with a cycle-detecting garbage collector for objects that refer to each other.

The jaadu ties colourful luggage tags onto one big suitcase on an airport baggage belt while a porter wheels away an untagged bag.

Think of it like this

Luggage tags on suitcases

A suitcase (the object) sits on the airport belt. Variables are luggage tags tied to it, and one suitcase can carry many tags. When the last tag is cut off, nobody can claim it, so staff take it away. Python counts the tags on every object and clears it the moment the count hits zero.

Watch it happen

Reference count of one list

a
0
-
1
-
2

1/5a = [1, 2, 3] creates a list object. One name points at it, so its count is 1.

The big ideas

What you need to know

Names are references

Assignment never copies. b = a makes b point to the same object, so changes through b show up through a when the object is mutable.

Reference counting

CPython keeps a count of references on every object and frees it as soon as the count reaches zero.

The cycle collector

Objects that point to each other never reach zero on their own. The gc module finds such unreachable groups and frees them.

is vs ==

== compares values, is checks if two names point to the very same object. Use is only for None, True and False.

See it in code

Walk through the code

python
1import gc2import sys3 4a = [1, 2, 3]5b = a                    # a second name for the same list6b.append(4)7print(a)                 # [1, 2, 3, 4]8print(a is b)            # True: same object9 10c = a.copy()             # a new list with the same items11print(a == c, a is c)    # True False12 13print(sys.getrefcount(a))  # 3 on Python 3.12: a, b and the call's own argument14del b15print(sys.getrefcount(a))  # 216 17loop = []18loop.append(loop)        # a list that contains itself: a reference cycle19del loop                 # its count never reaches 0 by itself20print(gc.collect())      # the cycle collector finds it; prints how many objects it freed

1/4b = a doesn't copy. Appending through b changes the one list both names share.

Run this line by line in a Python shell. The exact getrefcount numbers can differ between Python versions, but the rise and fall is what matters.

Save yourself the pain

Common mistakes

Oops

def add_item(item, basket=[]): ...

Do this instead

The default list is created once and shared across calls. Use basket=None and create a new list inside the function.

Oops

grid = [[0] * 3] * 3 to make a 3x3 grid.

Do this instead

That is three references to one inner list, so changing one row changes all. Use [[0] * 3 for _ in range(3)].

Oops

Using x is 1000 or name is "Ravi" to compare values.

Do this instead

Use ==. Identity checks on numbers and strings depend on caching details and can change between runs.

Your mission

Spot the shared object

~20 min

Quick check

After a = [1, 2]; b = a; b.append(3), what is a?

Go deeper

  1. 1Use sys.getrefcount and id() to watch references to an object.
  2. 2Create two objects that reference each other and read how the gc module handles them.
  3. 3Use sys.getsizeof to compare the memory of a list and a generator.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge