## How Python Manages Memory
Python manages memory automatically using a combination of two subsystems: **Reference Counting** and the **Generational Garbage Collector**.
### 1. Reference Counting
Every object in CPython contains a field called `ob_refcnt`, which tracks how many references point to it.
- When a variable is bound, the count increases.
- When a reference goes out of scope or is deleted, the count decreases.
- If the count drops to zero, Python instantly deallocates the memory.
### 2. Generational Garbage Collection
Reference counting cannot detect reference cycles (e.g., Object A references Object B, and Object B references Object A, but neither is accessible from the root scope).
- Python uses a cycle detector that groups objects into three generations (Gen 0, Gen 1, Gen 2).
- Newer objects go to Gen 0. If they survive a GC cycle, they move to Gen 1, and eventually Gen 2.
- Checks are run periodically. Gen 0 is checked frequently, while Gen 2 is checked rarely.
Understanding Python Memory Management: Garbage Collection Explained
"An in-depth guide to how Python manages memory under the hood, including reference counting, generational garbage collection, and avoiding memory leaks."
🛠️ Run calculations inside your browser
We provide a secure, native client-side tool matching this article topic. Perform your conversions, format tags, or test code values locally.