Skip to content

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 immediately deallocated. Python’s separate cyclic garbage collector handles reference cycles that reference counting alone can’t reclaim.

Example

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

Language: Python
>>> import sys

>>> greeting = "Hello, World!"  # A reference to the string
>>> sys.getrefcount(greeting)
2

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

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

>>> del greeting  # No more references (garbage collection time)

In this example, the sys.getrefcount() function returns the reference count for the object "Hello, World!". 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 June 1, 2026 • Reviewed by Dan Bader