Memory Management & Garbage Collection
Published by Brayan K
Python may look simple on the surface, but underneath it has a powerful and complex memory management system. To write high-performance Python — whether you're building ML pipelines, backend servers, or tools that process millions of objects — you must understand how Python allocates and frees memory, reference counting, garbage collection cycles, memory fragmentation, and how to track leaks and optimize memory usage.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
del removes a name, not the object
This lesson follows an object from the moment nothing refers to it any more to the moment its memory is free, and measures memory with sys.getsizeof() and tracemalloc. Three neighbours have lessons of their own: how fast code runs is Profiling & Optimising Python Performance, references that don't keep an object alive are Weak References (weakref), and making each object smaller is __slots__ & Memory Optimization. The lifetime and reference-count observations here describe ordinary GIL-enabled CPython builds, including the Python inside this site's Run button. Free-threaded builds and other implementations can manage references and reclamation differently. These examples also run in the browser.
A variable is a name that refers to an object, as Variables and Data Types showed: backup = report makes a second name for the same object, not a copy. del report removes the name report, and CPython frees the object only when nothing refers to it any more.
To show the moment an object is freed, the examples give their class a __del__ method. Like __init__ in Object-Oriented Programming, it's a special method that Python calls for you: CPython calls __del__ just before it frees the object. Here it only prints, so you can watch. It isn't the place for cleanup, as a question at the end of the lesson explains.
class Report:
def __init__(self, title):
self.title = title
def __del__(self):
print(self.title, "freed")
report = Report("sales")
backup = report
del report
print("after del report")
del backup
print("after del backup")
# ✅ Expected output:
# after del report
# sales freed
# after del backupdel report printed nothing, because backup still referred to the object. The language reference puts it this way: "del x doesn't directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x's reference count reaches zero."
A list's item, a dictionary's value and an object's attribute are references too. Taking the entry out of the dictionary removed the object's last reference:
class Report:
def __init__(self, title):
self.title = title
def __del__(self):
print(self.title, "freed")
inbox = {"today": Report("daily")}
del inbox["today"]
print("removed from the dict")
# ✅ Expected output:
# daily freed
# removed from the dictdel on an item changes the object; del on a name doesn't. Both names below see the list lose its first item, and deleting one of the names leaves the list alone, as with the aliases in Lists and Collections:
numbers = [10, 20, 30]
alias = numbers
del numbers[0]
print(alias)
del numbers
print(alias)
# ✅ Expected output:
# [20, 30]
# [20, 30]After del, the name is gone, and using it is a NameError:
scores = [70, 85]
del scores
print(scores)
# ✅ Expected error:
# NameError: name 'scores' is not definedsys.getrefcount() counts the references, plus one
CPython keeps a count of the references to each object, its reference count, and frees the object when the count reaches zero. sys.getrefcount() returns it:
import sys
data = []
print(sys.getrefcount(data))
alias = data
print(sys.getrefcount(data))
box = [data, data]
print(sys.getrefcount(data))
del alias, box
print(sys.getrefcount(data))
# ✅ Expected output:
# 2
# 3
# 5
# 2Each number is one more than you might expect. The function's docstring says why: "The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount()." So a new list with one name reports 2, a second name makes 3, and box adds two more, one for each of its items. Counting the change from a starting point leaves that extra one out:
import sys
data = []
before = sys.getrefcount(data)
alias = data
box = [data]
print(sys.getrefcount(data) - before)
del alias
print(sys.getrefcount(data) - before)
# ✅ Expected output:
# 2
# 1Ask only about objects your program made, and outside a function call. Inside a function, the count of an argument also includes references that Python holds for the call, and those differ between versions: for the same list, a function returning sys.getrefcount(arg) gave 5 on Python 3.10, 4 on 3.11–3.13 and 3 on 3.14. Objects that Python shares everywhere tell you nothing: in one program, sys.getrefcount(1) printed 126 on Python 3.10, 1000000089 on 3.11, 4294967295 on 3.12 and 3.13, and 3221225472 on 3.14. From 3.12, objects such as None and small numbers are immortal: Python never frees them, and their count stays fixed.
An object is freed when its last reference goes
Objects don't live until the program ends. A function's local variables are references, and they go when the function returns:
class Report:
def __init__(self, title):
self.title = title
def __del__(self):
print(self.title, "freed")
def make_report():
draft = Report("draft")
print("working on it")
make_report()
print("make_report() returned")
# ✅ Expected output:
# working on it
# draft freed
# make_report() returnedGiving a name a new object drops the name's reference to the old one, which frees it if that was the last. Setting a name to None, as the example's last lines do, frees the object just as del would, and keeps the name:
class Report:
def __init__(self, title):
self.title = title
def __del__(self):
print(self.title, "freed")
current = Report("v1")
current = Report("v2")
print("reassigned")
current = None
print("done")
# ✅ Expected output:
# v1 freed
# reassigned
# v2 freed
# doneThis is how CPython works, not a rule of the Python language. Its reference manual calls it an implementation detail: CPython "collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references". Circular references have a section of their own below. And freed means the memory goes back to CPython's own allocator, to be reused for the next objects. When it goes back to the operating system is the last section's subject.
A leak is a reference you forgot
Python frees whatever nothing refers to, so a memory leak in Python is a reference that stays: in a closure, in a list at the top of the program, in a cache. As long as it stays, so does the object, and everything that object refers to.
A closure keeps the variables it uses, as Closures & Lexical Scope in Real Projects showed. Here read() uses big, so the report lives as long as the function does:
class Report:
def __init__(self, title):
self.title = title
def __del__(self):
print(self.title, "freed")
def make_reader():
big = Report("big data")
def read():
return big.title
return read
reader = make_reader()
print("reader made:", reader())
del reader
print("reader deleted")
# ✅ Expected output:
# reader made: big data
# big data freed
# reader deletedA list at the top level of the program keeps everything put in it. Deleting your own name for an object doesn't take it out of the list:
class Window:
def __init__(self, name):
self.name = name
open_windows.append(self)
def __del__(self):
print(self.name, "freed")
open_windows = []
w = Window("settings")
del w
print("after del w:", len(open_windows))
open_windows.clear()
print("after clear")
# ✅ Expected output:
# after del w: 1
# settings freed
# after clearIn a program that runs for days, such a list grows with every request until the computer runs out of memory. The fix is to remove the reference: clear() here, or taking each item out when you're done with it. The tracemalloc section below shows how to watch memory grow.
Objects that refer to each other wait for the collector
Two objects that refer to each other form a cycle. Delete every name for them and each still has a reference, from the other one, so neither count reaches zero. CPython's cycle collector, the gc module, finds groups of objects that nothing else can reach and frees them. It runs by itself from time to time, and gc.collect() runs it now:
import gc
class Node:
def __init__(self, name):
self.name = name
self.other = None
def __del__(self):
print(self.name, "freed")
gc.collect()
a = Node("a")
b = Node("b")
a.other = b
b.other = a
del a, b
print("names deleted")
gc.collect()
print("collected")
# ✅ Expected output:
# names deleted
# a freed
# b freed
# collectedThe first gc.collect() clears anything already waiting, so that the collector doesn't happen to run by itself in the middle of the example. gc.collect() returns how many unreachable objects it found. Two lists that hold each other make 2:
import gc
gc.collect()
x = []
y = [x]
x.append(y)
del x, y
print(gc.collect())
# ✅ Expected output:
# 2Count lists, as here, rather than objects of your own classes: two such objects in a cycle gave 2 on Python 3.11–3.14 and in the Run button, but 4 on Python 3.10, which also counted each object's dictionary of attributes.
You rarely need to call it yourself, because the collector runs on its own as a program creates lists, dicts and objects. Below, 10,000 pairs of nodes are left in cycles. Some had already been freed before the program called gc.collect(), which freed the rest:
import gc
freed = []
class Node:
def __init__(self):
self.other = None
def __del__(self):
freed.append(1)
for _ in range(10_000):
a = Node()
b = Node()
a.other = b
b.other = a
del a, b
print(len(freed) > 0)
gc.collect()
print(len(freed))
# ✅ Expected output:
# True
# 20000It only watches objects that can refer to other objects. A number or a string can't be part of a cycle, so the collector ignores it, and gc.is_tracked() says whether it's watching an object:
import gc
print(gc.is_tracked(42), gc.is_tracked("text"))
print(gc.is_tracked([]), gc.is_tracked({"a": []}))
# ✅ Expected output:
# False False
# True TrueTracking is an implementation detail that can change with a dict's contents and the Python version. Some dicts containing only atomic values are untracked; Python 3.14 tracks nonempty dicts more broadly, while an empty dict can still be untracked. Use gc.is_tracked() to inspect a particular object.
Two settings come up in older advice. gc.disable() switches the cycle collector off, while reference counting still frees everything else. In this site's editor it would stay off for every later Run on the page, which is why no example here calls it. gc.get_threshold() shows when the collector runs by itself, and its numbers changed in Python 3.13: they were (700, 10, 10) before, and are (2000, 10, 10) from 3.13.
gc.collect() after del frees nothing more
A common habit is to follow del with gc.collect(), to free memory sooner. For ordinary objects it does nothing: del has already freed them, and the collector only looks for cycles. Here it finds nothing to free:
import gc
gc.collect()
big = list(range(100_000))
del big
print(gc.collect())
# ✅ Expected output:
# 0Call gc.collect() when you need cycles freed at a known moment, as the examples above do so that you can watch. Otherwise, leave the collector to run by itself.
sys.getsizeof() counts one object, not what it holds
sys.getsizeof() returns an object's size in bytes. For a list, that's the list itself, with its references to the items, but not the items. A list holding a one-letter string and a list holding a million-letter string are the same size:
import sys
small = ["a"]
large = ["a" * 1_000_000]
print(sys.getsizeof(small) == sys.getsizeof(large))
print(sys.getsizeof(large[0]) > 1_000_000)
# ✅ Expected output:
# True
# TrueSo it can't tell you how much memory your data uses. tracemalloc, from the standard library, counts the memory the code allocates while it's tracing. For a list of 10,000 short strings, it counted more than three times the list's own size:
import sys
import tracemalloc
tracemalloc.start()
words = ["word" + str(n) for n in range(10_000)]
used, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(used > 3 * sys.getsizeof(words))
# ✅ Expected output:
# Truegetsizeof() is still right for comparing one container with another. A tuple is a little smaller than a list of the same items, as Tuples said:
import sys
items = [3, 1, 4]
as_tuple = tuple(items)
print(sys.getsizeof(as_tuple) < sys.getsizeof(items))
print(sys.getsizeof(as_tuple) < sys.getsizeof(list(as_tuple)))
# ✅ Expected output:
# True
# TruePrint comparisons like these, never the sizes themselves, because sizes change between versions and computers. Here the tuple and the list took 64 and 88 bytes on Python 3.10–3.13, 72 and 88 on 3.14, and 32 and 44 in the Run button, whose Python is 32-bit.
Measuring memory with tracemalloc
tracemalloc.start() starts tracing, and tracemalloc.get_traced_memory() returns two numbers of bytes, (current, peak): current is the memory allocated since start() that is still in use, and peak is the most there has been at once. tracemalloc.stop() stops tracing. Freeing memory lowers current, but peak remembers:
import tracemalloc
tracemalloc.start()
data = list(range(100_000))
current_with, _ = tracemalloc.get_traced_memory()
del data
current_after, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(current_after < current_with, peak >= current_with)
# ✅ Expected output:
# True TrueAlways call stop() when you're done. In this site's editor, tracing would otherwise stay on for every later Run on the page.
With tracemalloc, a leak shows as growth. Each request below adds a 1,000-character string to a cache that is never emptied, so 1,000 more requests add more than 900,000 bytes:
import tracemalloc
cache = []
def handle(request):
cache.append(request * 1000)
tracemalloc.start()
handle("x")
before, _ = tracemalloc.get_traced_memory()
for n in range(1000):
handle("x")
after, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(len(cache), after > before + 900_000)
# ✅ Expected output:
# 1001 TrueTo find the line that allocated the memory, take a snapshot before and after, and compare them. compare_to() returns the differences, largest first, and each one has the line that allocated the memory and size_diff, the bytes it added. Print the line number, not the file's name, which differs from one computer to another:
import tracemalloc
tracemalloc.start()
before = tracemalloc.take_snapshot()
names = [str(n) for n in range(10_000)]
after = tracemalloc.take_snapshot()
tracemalloc.stop()
top = after.compare_to(before, "lineno")[0]
print(top.traceback[0].lineno)
print(top.size_diff > 0)
# ✅ Expected output:
# 5
# TrueA snapshot needs tracing switched on first:
import tracemalloc
tracemalloc.take_snapshot()
# ✅ Expected error:
# RuntimeError: the tracemalloc module must be tracing memory allocations to take a snapshottracemalloc also shows why generators save memory, as Generators & Iterators Mastery said. Summing a list of 100,000 squares builds the whole list first, while summing a generator expression makes one square at a time. The list's peak is more than 100 times the generator's:
import tracemalloc
def peak(make):
tracemalloc.start()
make()
_, top = tracemalloc.get_traced_memory()
tracemalloc.stop()
return top
list_peak = peak(lambda: sum([n * n for n in range(100_000)]))
gen_peak = peak(lambda: sum(n * n for n in range(100_000)))
print(list_peak > 100 * gen_peak)
# ✅ Expected output:
# TrueEqual numbers and strings that share one object
is asks whether two names refer to the same object, and == whether two values are equal, as Operators and Expressions taught. For some equal numbers is says True, which makes it look like a faster ==. It isn't one. CPython keeps a single object for each integer from -5 to 256 and hands out that object every time, while above 256 each calculation makes a new object:
a = int("256")
b = int("256")
c = int("257")
d = int("257")
print(a == b, a is b)
print(c == d, c is d)
# ✅ Expected output:
# True True
# True FalseThe edges of that range:
print(int("-5") is int("-5"), int("-6") is int("-6"))
# ✅ Expected output:
# True FalseEqual numbers written in the same program are shared too, which is why x = 1000 and y = 1000 can give one object, while two numbers made as the program runs don't:
x = 1000
y = 1000
print(x is y)
print(int("1000") is int("1000"))
# ✅ Expected output:
# True
# FalseStrings may be shared or not. Two equal strings made in different ways can be different objects, and sys.intern() returns the shared one:
import sys
a = "hello"
b = "".join(["hel", "lo"])
print(a == b, a is b)
print(sys.intern(b) is a)
# ✅ Expected output:
# True False
# TrueAll of this is CPython saving memory, and it can change between versions and between programs. Compare values with ==, and keep is for None.
Where the memory comes from, and when it goes back
On a computer, CPython gives every object of up to 512 bytes memory from an allocator of its own. That allocator takes memory from the operating system in blocks of 1 MiB, called arenas, split into pools of 16 KiB, as sys._debugmallocstats() reports on 64-bit Linux for Python 3.10–3.14. Freeing an object gives its memory back to that allocator, for the next objects. An arena goes back to the operating system only once every object in it has been freed. The Run button's Python doesn't use this allocator.
In one measurement on Linux, a list of 2,000,000 floats made the program about 80 MB bigger, and deleting the list gave 96 to 99% of that back to the system, on every version from 3.10 to 3.14. But when one float in every hundred was kept alive, deleting the rest gave back nothing: the survivors, spread through every arena, kept each arena in use. This is fragmentation, and it's why a program that runs for a long time can stay big after freeing most of what it made.
Practice: free a cycle
Make two nodes refer to each other, delete both names, and free the pair with the collector. Fill the three blanks: what the second node refers to, the statement that removes both names, and the gc function that frees the pair. If you get stuck, the 👉 lines under the code give the three answers in the order of the blanks.
import gc
class Node:
def __init__(self, name):
self.name = name
self.other = None
def __del__(self):
print(self.name, "freed")
gc.collect()
first = Node("first")
second = Node("second")
first.other = second
second.other = ___ # now each node keeps the other alive
___ first, second # remove both names
print("names deleted")
gc.___() # the cycle collector finds the pair and frees it
print("collected")
# 👉 replace ___ with first
# 👉 replace ___ with del
# 👉 replace ___ with collect
# ✅ Expected output:
# names deleted
# first freed
# second freed
# collectedLeave out gc.collect() and nothing frees the pair while the program runs. With python3 on a computer, the two freed lines come at the very end, after collected, as the program exits; in this site's editor, they appear during your next Run. And without the cycle, with second.other = None, del frees both nodes at once, before names deleted is printed.
On your own: measure the peak
Write peak_bytes(make). It starts tracemalloc, calls make(), reads the peak, stops tracing and returns (result, peak). Use it on sum([n * n for n in range(100_000)]) and on the same sum over a generator expression, each wrapped in a lambda. Print whether the two totals are equal, and whether the generator's peak was under 1% of the list's.
import tracemalloc
# your code hereimport tracemalloc
def peak_bytes(make):
tracemalloc.start()
result = make()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return result, peak
list_total, list_peak = peak_bytes(lambda: sum([n * n for n in range(100_000)]))
gen_total, gen_peak = peak_bytes(lambda: sum(n * n for n in range(100_000)))
print(list_total == gen_total)
print(gen_peak < list_peak / 100)
# ✅ Expected output:
# True
# TrueBoth sums are the same number. The list holds all 100,000 squares at once and the generator one at a time, so the generator's peak was thousands of times smaller on every version tried.
Practice quiz
Report's __del__ prints its title and "freed". After report = Report("sales") and backup = report, the program runs del report, print("deleted one name"), del backup and print("deleted the other"). What does it print?
- deleted one name, sales freed, deleted the other
- sales freed, deleted one name, deleted the other
- deleted one name, deleted the other, sales freed
- deleted one name, deleted the other
Answer: deleted one name, sales freed, deleted the other. del report removes one of the two names. The object is freed when del backup removes the last one.
At the top level of a program, data = [] and then alias = data. What does print(sys.getrefcount(data)) print?
- 1
- 2
- 4
- 3
Answer: 3. Two names refer to the list, and getrefcount's own argument is one more reference while it runs.
build() puts Report("draft") in a local variable and prints "building". The program calls build(), then prints "done". Report's __del__ prints its title and "freed". What is printed?
- building, done, draft freed
- building, draft freed, done
- draft freed, building, done
- building, done
Answer: building, draft freed, done. The local variable was the only reference, and it goes when build() returns, before done is printed.
Two Node objects, left and right, refer to each other through .other, and Node's __del__ prints its name and "freed". After del left, right, the program prints "deleted", calls gc.collect() and prints "collected". What is printed?
- left freed, right freed, deleted, collected
- deleted, collected, left freed, right freed
- deleted, left freed, right freed, collected
- deleted, collected
Answer: deleted, left freed, right freed, collected. Each node still refers to the other, so del frees nothing. gc.collect() finds the pair that nothing else can reach and frees it.
a = int("257") and b = int("257"). What does print(a == b, a is b) print?
- True True
- False False
- False True
- True False
Answer: True False. Equal values, two objects: CPython keeps a single object only for each integer from -5 to 256.
What does print(sys.getsizeof(["hi"]) == sys.getsizeof(["hi" * 100_000])) print?
- False
- True
- It depends on the Python version
- It stops with TypeError
Answer: True. getsizeof() counts the list itself, which holds one reference either way. The strings it refers to aren't counted.
A program imports tracemalloc, runs snapshot = tracemalloc.take_snapshot() without calling tracemalloc.start(), then prints "snapshot taken". What happens?
- It prints snapshot taken
- It prints an empty snapshot
- It stops with RuntimeError: the tracemalloc module must be tracing memory allocations to take a snapshot
- It stops with NameError: name 'snapshot' is not defined
Answer: It stops with RuntimeError: the tracemalloc module must be tracing memory allocations to take a snapshot. A snapshot needs tracing switched on first, with tracemalloc.start().
numbers = [10, 20, 30] and alias = numbers. The program runs del numbers[0], then del numbers, then print(alias). What is printed?
- [20, 30]
- It stops with NameError: name 'numbers' is not defined
- [10, 20, 30]
- []
Answer: [20, 30]. del numbers[0] changed the one list both names referred to. del numbers removed only a name.
Continue this course
- Previous: Profiling & Optimising Python Performance
- Next: Type Hints & Static Typing with mypy — Add type annotations and catch bugs before runtime with mypy
- Quick reference: Python cheat sheet › Standard Library
Frequently asked questions
Should I put cleanup code in __del__?
No. The language reference says it isn't guaranteed to run for objects that still exist when the program ends, and an error raised inside it doesn't stop anything: Python prints the error, starting "Exception ignored", and the program carries on. Close files, locks and connections with with, as Context Managers & the with Statement in Depth teaches. To run a function when an object is freed, use weakref.finalize(), from Weak References (weakref).
Why do two different objects sometimes have the same id()?
id() is only "guaranteed to be unique among simultaneously existing objects", as its docstring says. In id([1]) == id([2]), the first list is freed as soon as id() returns, and the second one can reuse its memory: that comparison printed True on Python 3.10–3.14 and in this site's Run button. Compare the ids of objects only while both are alive.
Why does a list take more memory than its items need?
It keeps room to grow, so that most append() calls need no more memory. Appending one item at a time, a list's room grew to 4, 8, 16, then 24 items; a list made with [0] * 10 had room for exactly 10, and for 16 after one more append (Python 3.10–3.14 and this site's Run button). When most of its items are removed, a list shrinks again. A dict doesn't, but dict(table) makes a smaller copy.
What is a weak reference?
A reference that doesn't keep its object alive. weakref.ref(obj) returns a reference you call to get obj back; once the object has been freed, calling it returns None. Weak References (weakref) teaches them.
Does __slots__ save memory?
Yes. An object of a class with __slots__ has no dictionary for its attributes, so each one takes less memory; how much depends on the class and the Python version. __slots__ & Memory Optimization teaches it.