Reference counts and immediate cleanup
We print differences, never raw counts, because raw numbers depend on the Python version.
CPython frees most objects the instant their reference count hits zero, and a separate cycle collector (the gc module) cleans up objects that keep each other alive. weakref lets you refer to an object without keeping it alive, and del removes a name, not the object.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create an instance, store it twice in a dict, and print how many extra references that adds. Delete the dict and print again.
Make a weak reference to an instance, delete the instance, and show that the reference now returns None.
Create two Node objects that point at each other, delete both names and show that they are freed only after gc.collect() (disable the automatic collector first).
Explain it without notes
How does CPython decide when to free an object? What are the cases that reference counting cannot handle?
What does del x do?
What is a weak reference and when would you use one?
How would you look for a memory leak in a long-running Python service?
Expected output
after y = x: + 1
after a list holds it twice: + 3
after del box: + 1
after del y: + 0
seen from inside a function: + 1
rebinding n ...
freed first
deleting n ...
freed second
done