Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Home Community How does garbage collection work in Python?

How does garbage collection work in Python?

Coding Now Expert  •  Jun 13, 2026  •  70 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)
```

**Memory management tools:** `tracemalloc`, `objgraph`, `memory_profiler`
0

0 Answers

Your Answer

Will not be displayed publicly
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →