How to Fix MemoryError in Python
In this tutorial, you'll learn about How to Fix MemoryError in Python. We cover key concepts, practical examples, and best practices.
Python raises MemoryError when the interpreter cannot allocate enough memory for an operation, exhausting available RAM.
The Wrong Way
data = [0] * 10**9 # allocate 1 billion integers
print(len(data))
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
data = [0] * 10**9
MemoryError
The Right Way
Process data in chunks or use memory-efficient data structures:
import numpy as np
# Use a memory-efficient array instead of a list
data = np.zeros(10**9, dtype=np.int8)
print(f"Allocated {data.nbytes / 1e9:.2f} GB")
Step-by-Step Fix
1. Use generators instead of lists
# Memory-heavy version
def squares_list(n):
return [i**2 for i in range(n)]
# Memory-efficient version
def squares_generator(n):
for i in range(n):
yield i**2
gen = squares_generator(10**7)
for _ in range(5):
print(next(gen))
2. Process files line by line
# Wrong -- loads entire file
with open('large_file.txt') as f:
content = f.read()
for line in content.splitlines():
process(line)
# Right -- reads one line at a time
with open('large_file.txt') as f:
for line in f:
process(line)
3. Use array module for numeric data
from array import array
# List of 10M floats = ~80MB
big_list = [0.0] * 10_000_000
# Array of 10M floats = ~40MB
big_array = array('d', [0.0]) * 10_000_000
4. Monitor memory usage
import sys
obj = [1, 2, 3] * 1000000
print(f"Size: {sys.getsizeof(obj) / 1e6:.2f} MB")
5. Use memory profiling tools
pip install memory-profiler
python3 -m memory_profiler script.py
Prevention Tips
- Use generators for large data sequences.
- Process files line by line instead of loading entirely.
- Use
numpyorarrayfor numeric data. - Set memory limits with
resource.setrlimit()if applicable. - Use
gc.collect()to free memory after large operations.
Common Mistakes with memory error
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro