Hackforge Academy

Category: python

Reference Counting Basics

Published on 27 Oct 2026

Explanation

In CPython, reference counting tracks references to objects. When a count reaches zero, an object can generally be reclaimed.

Code:

import sys
values = [10, 20]
print(sys.getrefcount(values))

Explanation

Several names can refer to one object; removing one binding leaves other references intact.

Code:

first = [1, 2]
second = first
third = first
del first
third.append(3)
print(second)

Explanation

del removes a name binding or item, but it does not necessarily destroy the referenced object.

Code:

data = [10, 20]
reference = data
del data
print(reference)

Explanation

Reference counting alone cannot reclaim mutually referencing objects when their counts remain above zero; cyclic collection complements it.

Code:

import gc
class Node: pass
a = Node(); b = Node()
a.other = b; b.other = a
del a, b
print(gc.collect())

Explanation

sys.getrefcount() is mainly a CPython debugging aid; it includes a temporary reference and exact values are implementation-dependent.

Code:

import sys
value = object()
print(sys.getrefcount(value))
other = value
print(sys.getrefcount(value))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community