How does Python manage memory and garbage collection?
Answer
Python uses private heap for objects, memory manager handles allocation. Reference counting: each object tracks references, deallocated when count reaches 0. Limitation: can't handle circular references. Generational GC: objects in 3 generations (0, 1, 2), younger collected more often. Cyclic garbage collector detects reference cycles using container traversal. Memory pools: small objects from pools (pymalloc), large from OS. Interning: small integers (-5 to 256) and short strings cached. Memory profiling: tracemalloc, memory_profiler. Avoid: circular references, large lists (use generators), holding references unnecessarily.
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.