MemoryError in Python — What It Means and How to Fix It
What Python's MemoryError exception means and how to resolve it.
Published October 28, 2026
MemoryError is raised when Python runs out of memory while allocating objects, such as building a huge list or loading a giant file.
What it means and why it happens
Typical causes: reading entire large files, creating massive lists or running 32-bit Python.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
MemoryError
Practical examples
Code that triggers it
data = list(range(10**10))The fix
total = 0
for i in range(10**10):
total += i
if i > 1000: break # iterate lazilyStream data
with open('big.log') as f:
for line in f:
process(line)Common mistakes
- Loading whole datasets into memory.
- Using lists where generators suffice.
- Memory leaks in long-lived processes.
Key takeaways
- MemoryError: MemoryError is raised when Python runs out of memory while allocating objects, such as building a huge list or loading a giant file.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
How do I find memory hogs?
Use tracemalloc or memory_profiler.
How do I find which line caused MemoryError?
The error message and stack trace show the file and line; start there and work backwards.