Skip to content

How to Fix MemoryError in Python

DodaTech Updated 2026-06-24 2 min read

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 numpy or array for numeric data.
  • Set memory limits with resource.setrlimit() if applicable.
  • Use gc.collect() to free memory after large operations.

Common Mistakes with memory error

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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

### What is the maximum memory Python can use?

Python can theoretically use all available system RAM plus swap space. On 32-bit systems, the limit is about 2-4 GB. On 64-bit systems, the limit is the available physical memory.

Why does a small list cause MemoryError?

Creating a list of 10 million Python objects uses more memory than you might expect. Each Python object has overhead (28+ bytes per object). A list of 10 million small integers can use 200+ MB.

How do I free memory in Python?

Python's garbage collector handles most memory automatically. Use del variable to remove references, then gc.collect() to force garbage collection. However, memory fragmentation may prevent release to the OS.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro