Home›Community›How does garbage collection work in Python?
How does garbage collection work in Python?
Coding Now Expert •
Jun 13, 2026 •
97 views
Python uses two mechanisms for memory management:
**1. Reference Counting (primary):**
Every object has a reference count. When it reaches 0, memory is freed immediately.
```python
x = [1, 2, 3] # ref count = 1
y = x # ref count = 2
del x # ref count = 1
del y # ref count = 0 → memory freed
```
**2. Cyclic Garbage Collector (secondary):**
Handles circular references that reference counting can't catch.
```python
a = {}
b = {}
a['b'] = b # a references b
b['a'] = a # b references a
# Both have ref count > 0, but neither is reachable
# Python's GC detects and cleans this
```
**GC control:**
```python
import gc
gc.collect() # manually trigger collection
gc.disable() # disable GC (use carefully — only if no circular refs)
```