Course contentsShow
← Python
Lesson 28 of 1,0601. Foundations and EnvironmentFree lesson

Tracking Object Lifecycles with Reference Counting

You will understand how Python tracks the number of references to an object to determine when it is eligible for garbage collection.

Tracking Object Lifecycles with Reference Counting

In this lesson, you will learn how Python automatically manages your computer's memory by "counting" how many variables are pointing to a specific object.

The "How Many People Are Watching?" Rule

Think of a Python object—like a list or an integer—as a performance on stage. Python wants to keep that performance running as long as someone is watching it. In Python, "watching" means having a variable name assigned to that object.

Python keeps a running tally called a reference count. Every time you assign an object to a new variable, the count goes up. Every time you delete a variable or reassign it to something else, the count goes down.

Seeing it in Action

When the reference count hits zero, it means no one is watching the object anymore. Python immediately cleans it up to free up your computer's memory. This process is called garbage collection.

You can see this in practice with the sys module, which lets us peek at the reference count:

import sys

# Create an object
my_list = [1, 2, 3]

# Check the reference count (it's usually 1 or 2 due to internal tracking)
print(sys.getrefcount(my_list))

# Assign it to a second variable
another_list = my_list

# The reference count has now increased!
print(sys.getrefcount(my_list))

# Delete one variable
del another_list

# The count drops back down
print(sys.getrefcount(my_list))

Why does this matter?

You don't need to manually tell Python to "delete" objects; you just need to stop using them. When a variable goes out of scope (for example, when a loop ends or a function finishes), the reference count of the objects it pointed to decreases. If those counts hit zero, Python silently clears them away. This prevents your program from using up all your computer's memory unnecessarily. It is the invisible backbone of Python's memory management.

Key Takeaway: Python keeps an object alive as long as its reference count is greater than zero; once no variables point to an object, Python automatically reclaims its memory.