Reference Count

In Python, the reference count is a mechanism used by the interpreter to manage memory allocation and deallocation for objects.

Every object in Python has an associated reference count, which keeps track of the number of references pointing to that object. When you create a new reference to an object, its reference count increases by one. In contrast, when a reference is deleted or goes out of scope, the reference count decreases by one. Once the reference count drops to zero, the object is no longer needed, and Python’s garbage collector can reclaim the memory.

Example

Here’s a example to demonstrate how reference counting works in Python:

Python
>>> import sys

>>> number = 42  # A reference to 42
>>> sys.getrefcount(number)
2

>>> value = number  # Create a new reference, value
>>> sys.getrefcount(number)
3

>>> del value  # Delete the value reference
>>> sys.getrefcount(a)
2

>>> del number  # No more refereces (Garbage collection time)

In this example, the sys.getrefcount() function returns the reference count for the object 42. Note that the reference count is initially 2 because getrefcount() temporarily adds its own reference to the object.

Tutorial

Memory Management in Python

Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, you’ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Python’s internal memory management algorithms.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 24, 2024 • Reviewed by Dan Bader