Python manages memory for you using a combination of heap allocation, reference counting, and a garbage collector for cleaning up unused objects. Understanding how memory works helps you write faster, safer programs and avoid memory leaks.
gc module cleans up unreachable objects (e.g., reference cycles).Important tools for inspecting and controlling memory in Python:
id(obj) – returns a unique identifier for the object (often its memory address).sys.getrefcount(obj) – shows how many references point to an object.gc.collect() – manually trigger a garbage-collection run.del name – remove a reference (name) to an object.
import sys
a = [1, 2, 3]
b = a # b references the same list object
c = a # c also references the same list
print(id(a), id(b), id(c)) # all ids are the same
print(sys.getrefcount(a)) # reference count (a, b, c + internal temp refs)
del b # remove one reference
print(sys.getrefcount(a)) # reference count decreases
del a
del c # after this, the list has no references and can be freed
import gc
class Node:
def __init__(self):
self.ref = None
# create a reference cycle
a = Node()
b = Node()
a.ref = b
b.ref = a
# break all external references
del a
del b
# the two Node objects reference each other,
# so reference counting alone can't free them.
# gc.collect() finds and frees them.
collected = gc.collect()
print("Unreachable objects collected:", collected)
sys.getrefcount() reveals how many active references exist for a given object.gc.collect() forces a garbage-collection pass that detects and frees such cycles.with blocks).tracemalloc and profilers to investigate memory usage in large projects.sys.getsizeof().gc.collect() to see how many objects are collected.tracemalloc to track which lines of code allocate the most memory in a small program.