Category: python
Reference Counting Basics
Published on 27 Oct 2026
Explanation
In CPython, reference counting tracks references to objects. When a count reaches zero, an object can generally be reclaimed.
Code:
import sys values = [10, 20] print(sys.getrefcount(values))
Explanation
Several names can refer to one object; removing one binding leaves other references intact.
Code:
first = [1, 2] second = first third = first del first third.append(3) print(second)
Explanation
del removes a name binding or item, but it does not necessarily destroy the referenced object.
Code:
data = [10, 20] reference = data del data print(reference)
Explanation
Reference counting alone cannot reclaim mutually referencing objects when their counts remain above zero; cyclic collection complements it.
Code:
import gc class Node: pass a = Node(); b = Node() a.other = b; b.other = a del a, b print(gc.collect())
Explanation
sys.getrefcount() is mainly a CPython debugging aid; it includes a temporary reference and exact values are implementation-dependent.
Code:
import sys value = object() print(sys.getrefcount(value)) other = value print(sys.getrefcount(value))