names · globals()objects · the heapalistb1a = [1, 2]2b = a3b.append(3)4c = [1, 2, 3]5print(a == c, a is c)6del a7b = NoneNoneTypeNoneclist[1, 2].append(3)[1, 2, 3]True False
Code card: refs.py; the highlighted line is the one runningName tags in the namespace: the names your program madeObjects on the heap: type, reference count and valueArrows: which object each name refers to right nowPython keeps names and objects apart: a name in a namespace refers to an object on the heap, and the arrow from a name tag to an object is that reference. Running refs.py: line 1 builds a list and a refers to it; line 2 makes b refer to the same list, so its count is 2; line 3 changes that one list through b and a sees it too; line 4 builds a second, equal list for c; line 5 prints True False (equal values, different identities). Line 6 deletes the name a, not the list. Line 7 moves b to None: the list's count falls to 0 and CPython frees it at once.

Names and objects

  1. Python keeps names and objects apart. An object holds the data and has an identity, a type and a value. A name lives in a namespace, a table that maps each name to one object. Names never hold data themselves.

Sharing one object

Letting go

Try it yourself

;; step 1/8
>>> a = [1, 2]
>>> 'a' in globals()     # the module's namespace is a dict
True
>>> type(a)
<class 'list'>
>>> id(a)                # identity: unique while it lives
4377851840               # yours will differ

The counts in the figure count only this program's names. CPython's real reference count also includes every other reference, such as a slot in a list or a function's argument; sys.getrefcount() shows it, usually one higher than you expect because the call itself holds a reference. Freeing an object the moment its count reaches zero is a CPython implementation detail. Other implementations, such as PyPy, may free it later. Objects that refer to each other in a cycle never reach zero on their own; CPython's cycle collector (the gc module) finds them.