Python automatically manages memory.
Objects are deleted when they are no longer used.
📌 Reference Counting
Every object tracks how many variables point to it.
When the count becomes 0, it is removed.
a = [1, 2, 3]
b = a
del a
del b
Reference count:
a → 1
a, b → 2
after del → 0
Object deleted
📌 Circular Reference Problem
Two objects pointing to each other
will never reach reference count 0.
class Node:
def __init__(self):
self.ref = None
a = Node()
b = Node()
a.ref = b
b.ref = a
del a
del b
Both objects still reference each other
Reference count ≠ 0
📌 Garbage Collector (GC)
Python’s GC:
• Detects unreachable cycles
• Breaks circular references
• Frees memory safely
🎯 Core Idea
Reference Counting → Main mechanism
GC → Handles circular references
