Skip to content

Garbage Collection

In one line

Garbage collection is Python's automatic memory management that frees memory occupied by objects no longer in use.

In simple words

Garbage collection (GC) is Python's automatic memory management system. It reclaims memory from objects that are no longer reachable from any reference, so you don't have to manually free memory like in C.

Python uses two mechanisms:

  1. Reference counting — each object has a count of references to it. When the count reaches zero, the object is immediately freed. This handles most cases.
  2. Cyclic GC — a periodic collector that finds and frees groups of objects referencing each other in a cycle (which reference counting alone cannot detect).

You rarely need to think about garbage collection in Python. The gc module lets you control it if needed: gc.collect() forces a collection, gc.disable() turns it off. The __del__ method runs when an object is about to be freed.

Example

python
import sys
import gc

# Reference counting
a = [1, 2, 3]
print(sys.getrefcount(a) - 1)  # 1 (one reference: a)

b = a
print(sys.getrefcount(a) - 1)  # 2 (a and b)

del b
print(sys.getrefcount(a) - 1)  # 1 (only a)

# Force garbage collection
collected = gc.collect()
print(f"Collected {collected} objects")

Python uses reference counting + cyclic GC for automatic memory management. The gc module provides control.

Common confusions

  • Confused with: manual memory management

    The difference: Garbage collection automatically frees memory when objects are no longer referenced. Manual memory management (C/C++) requires the programmer to explicitly allocate and free memory. Python's GC prevents memory leaks and use-after-free bugs.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary