Reference Counting

say it: “REF-er-ens KOWN-ting” /ˈrɛfərəns ˈkaʊntɪŋ/

Python counts what points to an object and frees it when the count hits zero.

What is reference counting?

Reference counting is how Python knows when an object is no longer needed: it counts how many names and containers point to it, and frees the memory when the count reaches zero.

import sys
cart = ["book"]
saved = cart
print(sys.getrefcount(cart))  # 3: cart, saved, and the call itself

Level: Master · More Python terms at this level

Updated