Reference counting

Python and various other programming languages employ reference counting, a memory management approach, to automatically manage memory by tracking how many times an object is referenced. A reference count, or the number of references that point to an object, is a property of each object in the Python language. When an object’s reference count reaches zero, it becomes un-referenceable and its memory can be freed up.

Examples :

Example 1: Simple Reference Counting

Python3




# Create an object
x = [1, 2, 3]
 
# Increment reference count
y = x
 
# Decrement reference count
y = None


Example 2: Reference Counting with Cyclic Reference

Python3




# Create two objects that refer to each other
x = [1, 2, 3]
y = [4, 5, 6]
x.append(y)
y.append(x)


Example 3: Using the sys.getrefcount() function

Python3




import sys
 
# Create an object
x = [1, 2, 3]
 
# Get reference count
ref_count = sys.getrefcount(x)
 
print("Reference count of x:", ref_count)


Output :

Reference count of x: 2

Garbage Collection in Python

Python’s memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory similar to using dynamic memory allocation in languages such as C or C++
Python uses two strategies for memory allocation: 

  1. Reference counting
  2. Garbage collection

Similar Reads

Reference counting

Python and various other programming languages employ reference counting, a memory management approach, to automatically manage memory by tracking how many times an object is referenced. A reference count, or the number of references that point to an object, is a property of each object in the Python language. When an object’s reference count reaches zero, it becomes un-referenceable and its memory can be freed up....

Garbage collection

...

Advantages and Disadvantages

...

Contact Us