MemoryError is raised when a Python operation cannot allocate enough memory to complete. Unlike most languages, Python raises an exception rather than crashing, giving you a chance to free resources. However, by the time it is raised, the system is usually under extreme pressure.
Why it happens
- •Creating an enormous list, dict, or string that exceeds available RAM.
- •Loading a large file entirely into memory instead of streaming it.
- •A memory leak accumulates objects over time until RAM is exhausted.
- •Running many processes simultaneously on a machine with limited RAM.
Examples
Code that triggers the error
# Allocating a huge list that exhausts RAM
data = [0] * (10 ** 10)Error output
MemoryError
How to fix it
Use generators and iterators to process data in chunks instead of loading everything at once. For large files, read line by line or use memory-mapped files. Profile memory usage with tracemalloc to find the source of high allocation.
Fixed code
# Use a generator instead of materializing the full list
def big_range(n):
for i in range(n):
yield 0
for item in big_range(10 ** 10):
break # process one at a timeRelated errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free