MemoryError: Creating Large List

MemoryError

Quick Answer

You are creating a list too large to fit in memory. Use range() directly for iteration or generator expressions for lazy evaluation.

Why This Happens

Creating a list with billions of elements consumes massive memory. range() is lazy and uses constant memory. Generator expressions also produce values lazily.

The Problem

numbers = list(range(1_000_000_000))

The Fix

for n in range(1_000_000_000):
    process(n)

# Generator expression instead of list comprehension:
total = sum(x**2 for x in range(1_000_000_000))

Step-by-Step Fix

  1. 1

    Use range() directly

    Iterate over range() without converting to list.

  2. 2

    Use generator expressions

    Replace [x for x in items] with (x for x in items).

  3. 3

    Use itertools

    Functions like itertools.islice() process data lazily.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free