Log inStart free
LESSON 1.08 · 6 STAGES · 2 CONTROLS · 2 CHECKSPRO · PREVIEW

Python memory management

Watch reference counts rise and fall, and see the collector free a cycle.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 2 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.08 · MEMORY BAYCOUNT a 1 · b 2
01
Stage 1 of 6 · Count references
Each reference adds 1 to an object's reference count. Node b has 2: the name b and a.next.
Explain it simply

The function main makes two Node objects, the boxes on the right. Each object keeps a count of the references that point to it. That's its reference count. Node b has two arrows coming in, from the name b and from a.next, so its count is 2.

Node a has a count of 1, from a. Node b has a count of 2, from b and a.next.

frame and nameobjectreference and countreachable, outputunreachableweak reference, freed
programframeobjectsoutputmaindef main():1a = Node("a")2b = Node("b")3a.next = b4b.next = a5del a6del b7print(gc.collect())abNode · id 2432count1name'a'nextNode · id 2480count2name'b'nextNone(nothing yet)programframeobjectsoutputmaindef main():1a = Node("a")2b = Node("b")3a.next = b4b.next = a5del a6del b7print(gc.collect())abNode · id 2432count1name'a'nextNode · id 2480count2name'b'nextNone(nothing yet)
Toy: 2 Nodes, 1 weakref · CPython 3.12 rules · ids are stand-ins · interpreter objects left out
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
count(x)=number of references to x\sy{cnt}{param}{\mathrm{count}}(\sy{x}{data}{x}) = \text{number of}\ \sy{ref}{param}{\text{references}}\ \text{to}\ x
count(b)=1 (b)+1 (a.next)=2;count(a)=1 (a)=1\mathrm{count}(\texttt{b}) = 1\,(\texttt{b}) + 1\,(\texttt{a.next}) = 2;\quad \mathrm{count}(\texttt{a}) = 1\,(\texttt{a}) = 1

An object's count is the number of references that point to it.

Common mix-ups

MYTHdel a deletes the object that a points to.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
2 CHECKS · PRO
Q01With b.next = None, when is Node a freed?

Make your guess, then test it in the diagram. All 2 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 2 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.