Skip to content

MemoryError

Error message

                MemoryError
              

Quick summary

Your program tried to allocate more memory than is available.

Why this happens

  • Creating a very large list or data structure

  • Loading a huge file entirely into memory

  • Infinite recursion or unbounded data growth

  • Memory leak from accumulating references

Minimal example

✗ Broken code
# Trying to create a huge list
big_list = [0] * 10**12  # MemoryError
✓ Fixed code
# Use a generator instead of a list
def zeros(n):
    for _ in range(n):
        yield 0

# Process one at a time, minimal memory
for z in zeros(10**12):
    pass  # Process each zero

Instead of creating a huge list in memory, use a generator that produces values one at a time.

How to diagnose

  • Check the size of data structures being created

  • Monitor memory usage with tools like memory_profiler

  • Look for unbounded loops or growing collections

How to fix

  • Process data in chunks instead of loading everything at once

  • Use generators for lazy evaluation

  • Free unused references (del variable, gc.collect())

  • Use more memory-efficient data structures

How to prevent

  • Use generators and iterators for large datasets

  • Process files line by line instead of reading all at once

  • Monitor memory usage in production

Related Resources

Related Glossary

Related Lessons

← Back to language