Python reference counting garbage collector example

Share Your Love

Here’s an example that demonstrates how reference counting garbage collectors work in Python:

import sys

# Create some objects
a = [1, 2, 3]  # Reference count of `a` is 1
b = a  # Reference count of `a` is incremented to 2

# Print reference counts
print(sys.getrefcount(a))  # Output: 3

# Remove one reference to `a`
b = None  # Reference count of `a` is decremented to 2

# Print reference count again
print(sys.getrefcount(a))  # Output: 2

In the example above, we create a list object a with the values [1, 2, 3]. We assign a to another variable b, which increases the reference count of a to 2. We then use the sys.getrefcount() function to retrieve the reference count of a and print it. It shows a reference count of 3 because getrefcount() itself creates a temporary reference to the object.

Next, we remove one reference to a by assigning None to b. This decreases the reference count of a to 2. Finally, we print the reference count of a again, and it shows a count of 2.

The example illustrates how reference counting keeps track of the number of references to an object. When the reference count of an object reaches zero, it means there are no more references to the object, and Python’s garbage collector can deallocate the memory occupied by that object.

Note that the sys.getrefcount() function returns the reference count including the temporary reference created by the function itself. So, the actual reference count of an object may be one less than the value returned by getrefcount().

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter