L6·Expert
🧠Memory, References & gc
id, is vs ==, refcounting, and the cycle collector.
gcidisrefcount
§ 1is vs ==
== compares values. is compares identity (same object in memory). id(x) returns the identity.
§ 2Refcounting
CPython deallocates when the refcount hits zero. sys.getrefcount(x) inspects it.
§ 3Cycles
Reference cycles (a→b→a) can't be freed by refcounting alone. The gc module collects them.
Example
1import sys, gc2a = [1, 2]3b = a4print(a is b, a == b) # True True5c = [1, 2]6print(a is c, a == c) # False True7print(sys.getrefcount(a)) # includes the temp arg8gc.collect()Try it live · Python runs in your browser
Loading playground…
Checkpoint quiz
Question 1 / 2
a == b tests: