Connect any database. Ask in plain English.

Try free
← Blog

Python MemoryError: What "Unable to Allocate X GiB" Means, the Arithmetic, and 7 Fixes (2026)

NumPy's "Unable to allocate" message is the size of one array: rows × columns × bytes per value, so a 100,000 × 100,000 float64 array asks for 74.5 GiB. Why the error appears with RAM free (32-bit Python, the Windows commit limit, container caps, Linux overcommit), reproduced safely on a 64 GB laptop and in a 512 MB container, and the fixes that worked.

Fastero Dev TeamFastero Dev Team2026-12-02

We read the NumPy source that writes the "Unable to allocate" message, then reproduced it on a Windows 11 laptop with 64 GB of RAM and in a Linux container capped at 512 MB, without ever filling memory. Every number below comes from that script or from the documentation it is checked against.

The short answer: MemoryError means Python asked the operating system for memory and was refused. NumPy's version names one array: multiply its dimensions by the bytes per value (8 for float64), so shape (100000, 100000) is 100,000 × 100,000 × 8 = 80 billion bytes, or 74.5 GiB. It can appear with RAM free when the limit is elsewhere: a 32-bit Python, the Windows commit limit, a container's memory cap or Linux's strict overcommit mode. Fix it by asking for less: a smaller dtype, chunks, np.memmap, a sparse matrix, or an algorithm that never builds the full matrix. A 64-bit Python and a bigger machine come after. Checked 2 December 2026.

Fastero

Connect your database. Ask questions. Get dashboards.

Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.

Try free →

What raises MemoryError in Python

Python's documentation says the exception is "Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects)." In practice it means one request for memory failed. It is raised at the request that failed, often the biggest one, which is not necessarily the code that used up the rest.

You will meet it in four forms:

What you see Where it comes from
MemoryError with no message Plain Python, for example bytearray(1 << 50), which asks for 1 PiB
Unable to allocate 74.5 GiB ... NumPy, which subclasses MemoryError and names the shape and dtype
MemoryError: bad allocation C++ code inside a package (see below)
No error: the process is killed Linux, when memory runs out after the allocation succeeded

The last row matters most in Jupyter. On Linux a large allocation often succeeds and the process is killed later, when it writes to the memory, so you never see a MemoryError: the notebook says the kernel died instead. That case has its own guide: the kernel appears to have died.

What numpy's "Unable to allocate" error means

NumPy builds the message in numpy/_core/_exceptions.py. It takes the dtype's item size, multiplies it by every dimension, and prints the result in binary units with three significant figures. That is why you sometimes see a stray period, as in 763. MiB: it is the formatter keeping three digits, not a typo.

So the number is the size of the array you asked for, worked out like this:

Shape and dtype Arithmetic Bytes NumPy prints
(100000, 100000) float64 100,000 × 100,000 × 8 80,000,000,000 74.5 GiB
(100000, 100000) float32 100,000 × 100,000 × 4 40,000,000,000 37.3 GiB
(3000000, 300) float32 3,000,000 × 300 × 4 3,600,000,000 3.35 GiB
(105284, 53946) uint32 105,284 × 53,946 × 4 22,718,602,656 21.2 GiB
(10000, 10000) float64 10,000 × 10,000 × 8 800,000,000 763. MiB

Two details trip people up. NumPy's units are binary: 1 GiB is 1,073,741,824 bytes, so 80 billion bytes is 74.5 GiB, not 80. And the figure is one request, not your total use. A user on Python's forum hit "Unable to allocate" for 21.2 GiB on a machine with 64 GB of RAM, about half of it in use; a reply suggested the code might be copying the array and failing on the third or fourth copy.

The shape tells you which line to look at:

  • (n, n), where n is your row count: a pairwise matrix. scikit-learn's pairwise_distances returns an "ndarray of shape (n_samples_X, n_samples_X)", which is 74.5 GiB for 100,000 rows.
  • A huge second dimension: one-hot encoding, get_dummies or a pivot that turned a column's values into columns.
  • A dtype of object or <U...: strings, which cost far more than numbers.

A table of how much memory a NumPy array asks for by shape and bytes per value: (10,000, 10,000) needs 763 MiB as float64, (1,000,000, 1,000) needs 7.45 GiB, (100,000, 100,000) needs 74.5 GiB as float64 and 37.3 GiB as float32, and (200,000, 200,000) needs 298 GiB

Memory one NumPy array asks for, in the units NumPy prints. Calculated with NumPy 2.5.5's own size formatter.

Check the size before you allocate

You don't need to hit the error to know it is coming. This is the function from our script:

import math
import numpy as np
 
def array_bytes(shape, dtype):
    """Bytes NumPy asks for: every dimension multiplied together, times bytes per item."""
    return math.prod(shape) * np.dtype(dtype).itemsize
 
n = array_bytes((100_000, 100_000), "float64")
print(f"{n:,} bytes = {n / 1024**3:,.2f} GiB")
80,000,000,000 bytes = 74.51 GiB

For an array you already have, a.nbytes gives the same figure. Compare it with free memory, and leave room for a copy: a + b or a.astype(...) builds a second array of the same size.

Reproduce the error safely

To see the real message without stressing the machine, ask for more than any 64-bit process can address. Microsoft's limits table gives a 64-bit process 128 TB of address space on current Windows, and the Linux kernel's x86-64 memory map gives user space about 128 TB too, so a request above that is refused at once and no memory is touched:

import numpy as np
 
np.empty((10_000_000, 10_000_000))  # 728 TiB
np.empty((10**10, 10**10))          # too big to even count in bytes

We ran it on 2 December 2026 with NumPy 2.5.5, on Windows 11 (Python 3.14.3) and in a Linux container (Python 3.14.10), with the same result on both:

MemoryError: Unable to allocate 728. TiB for an array with shape (10000000, 10000000) and data type float64
ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.

Don't test with a size that is merely too big for your RAM, such as 50 GiB. On Linux it can succeed and get the process killed later; on Windows it can make the page file grow.

Why MemoryError happens when you have free RAM

When the error appears with gigabytes free in Task Manager or free -h, the limit is somewhere other than RAM. There are four usual places.

1. A 32-bit Python. Microsoft's table gives a 32-bit process "2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared (default)", and 4 GB at most, however much RAM the machine has. Python's own docs say that to check, "it is more reliable to query the sys.maxsize attribute":

python -c "import sys; print(sys.maxsize > 2**32)"

True means 64-bit. If it prints False, install a 64-bit Python and recreate your environment.

2. The Windows commit limit. Windows promises memory before it is used, and stops promising at the commit limit. Microsoft: "The system commit memory limit is the sum of physical memory and all page files combined." And "If the system commit charge reaches the system commit limit, the system and processes might not get committed memory." Our laptop has 63.7 GiB of RAM and a 25 GB page file, for a commit limit of 88.7 GiB; when we ran the script, 27.4 GiB of RAM and 46.5 GiB of commit were free. A request bigger than the free commit fails even when RAM is free. Microsoft notes both figures "can be measured on the Performance tab in Task Manager".

One thing we didn't expect: on this 16-thread laptop, a fresh Python process went from 10 MiB to 501 MiB of committed memory just by running import numpy. It grew with the threads of OpenBLAS, NumPy's math library: 19 MiB with OPENBLAS_NUM_THREADS=1, 116 MiB with 4, 501 MiB with the default 16. Sixteen worker processes that each import NumPy would commit about 8 GiB before reading any data (our arithmetic, not a measurement). In the Linux container the process's resident memory after the import was 27 MiB whatever the setting.

3. A container or job limit. Docker's --memory, a Kubernetes limit or a JupyterHub server size caps one process or group, whatever the machine has. We capped a child process at 512 MiB with a Windows job object while the laptop had 27 GiB free:

np.zeros((10000, 10000), float64) -> MemoryError: Unable to allocate 763. MiB for an array with shape (10000, 10000) and data type float64
np.zeros((10000, 10000), float32) -> worked, 381 MiB

On Linux a container limit more often ends in a kill than a MemoryError. The Kubernetes docs say "memory limits are enforced by the kernel with out of memory (OOM) kills."

4. Linux overcommit. The kernel has three modes in /proc/sys/vm/overcommit_memory. Mode 0, the default, is a heuristic: "Obvious overcommits of address space are refused." Mode 1 always says yes. Mode 2 refuses any request that would take total commitments past swap plus a share of RAM: it is "not permitted to exceed swap + a configurable amount (default is 50%) of physical RAM", so on a server set to mode 2 you get MemoryError with half the RAM unused. In modes 0 and 1 the opposite can happen. Our container ran in mode 1 with a 512 MB limit, and this script:

import numpy as np
a = np.zeros((10_000, 10_000))          # 763 MiB asked for in a 512 MiB container
print(f"allocated {a.nbytes / 2**20:.0f} MiB without an error", flush=True)
a[:] = 1.0                               # now the pages are actually used
print("filled it")
$ python lazy.py
allocated 763 MiB without an error
exit status: 137
Killed

(The shell's Killed line arrived after our echo of the exit status.) The np.zeros call succeeded because Linux hands out pages only when they are written, and the process was killed when a[:] = 1.0 wrote to them. No MemoryError at all.

Cause How to check Fix
32-bit Python sys.maxsize > 2**32 is False Install 64-bit Python
Windows commit limit Task Manager, Memory, Committed Bigger or system-managed page file; fewer processes
Container or job limit docker stats, the pod's limit, the hub's server size Raise the limit or use less
Linux overcommit mode 2 cat /proc/sys/vm/overcommit_memory prints 2 Ask for less, or have the admin change it

Connect any database. Ask in plain English.

Start free →

What MemoryError: bad allocation means

This one comes from C++ code inside a package. When C++'s new can't get memory it throws std::bad_alloc; pybind11, which many packages use to call C++ from Python, translates std::bad_alloc into MemoryError. The message is the C++ library's: Microsoft's docs say "The value returned by what is an implementation-defined C string", and their example prints bad allocation, the wording in the error. The fixes are the same as for NumPy, plus the package's own settings for batch or tile size.

How to fix MemoryError

In the order we would try them, cheapest first:

  1. Use a smaller dtype. float32 halves memory and is enough for most data that came from a CSV; int8 or uint8 hold small integers in one byte. Under our 512 MiB cap, float64 failed and float32 worked. In pandas, set dtypes when reading and use category for repeated strings: see pandas out of memory.
  2. Work in chunks. pandas' guide to scaling puts it simply: "Some workloads can be achieved with chunking by splitting a large problem into a bunch of small problems." For CSVs, see reading a large CSV in pandas. For distance matrices, scikit-learn's pairwise_distances_chunked does what its docs say: "Generate a distance matrix chunk by chunk with optional reduction."
  3. Keep the array on disk with np.memmap. NumPy's docs: "Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory." Under the same 512 MiB cap on Windows, a 763 MiB float64 memmap filled 1,000 rows at a time left the process at 21 MiB of private memory. In the 512 MB Linux container it also finished without being killed. One exception: under an address-space cap (ulimit -v), the mapping itself failed with OSError: [Errno 12] Cannot allocate memory.
  4. Use a sparse matrix when most values are zero. A 100,000 × 100,000 matrix with 1,000,000 non-zero values took 11.8 MiB in SciPy's CSR format, against 74.5 GiB dense.
  5. Stop making copies. a *= 2 or np.multiply(a, 2, out=a) works in place; del large objects you no longer need. In Jupyter, the output history also keeps old results alive: see Jupyter notebook memory usage.
  6. Let a database or DuckDB do the heavy part. Aggregate in SQL and pull the result, or query files larger than memory with DuckDB. Dask splits arrays and DataFrames into chunks for you.
  7. Use a 64-bit Python, then a bigger machine. Only once the arithmetic says the work needs that much. How much RAM data science needs has the sizes.

When a bigger machine is the answer, and when it isn't

Fastero is an AI and data platform where people and AI agents work together on a team's data. Its notebooks are standard .ipynb files on a notebook server nobody has to run, and they run on 1 CPU and 2 GB as standard, so the fixes above matter there too. On the Pro plan, a notebook, app or Python run can move to a bigger machine:

Machine CPUs Memory Price
Standard (included) 1 2 GB Included
Medium 2 8 GB $0.20 an hour
Large 4 16 GB $0.40 an hour
Extra large 8 32 GB $0.80 an hour

Bigger machines are charged by the second from money you add to your balance, separate from what Pro includes. See pricing.

Use the arithmetic to decide. A (1,000,000, 1,000) float64 array is 7.45 GiB, or 8 billion bytes. Extra large holds it twice, for the copy that a + b makes, and a two-hour job costs $1.60 rather than a new laptop. Cast it to float32 first (3.73 GiB) and Large holds two copies at $0.40 an hour. A (100,000, 100,000) float64 matrix is 74.5 GiB, and even as float32 it is 37.3 GiB. At that size, chunking, a sparse matrix or pairwise_distances_chunked is the fix, and it costs nothing. The same goes for a dtype change that halves the array.

In a Fastero notebook, a SQL cell runs on a saved connection and hands its rows to Python as a pandas DataFrame named after the cell, so a GROUP BY in the database can replace millions of rows in memory.

A Jupyter notebook in Fastero: a pandas cell that compares twelve invented solar sites' output with their forecast, its table of results below, and the project's notebooks, queries and files in the explorer on the left

A notebook in Fastero, with its data typed into the cell. Sample data.

FAQ

What causes MemoryError in Python?

A request for memory that the operating system refused. Usually one large allocation, such as a NumPy array or a pandas DataFrame, asks for more than is available to the process, which may be less than the machine's free RAM.

How do I fix numpy's "Unable to allocate" error?

Multiply the shape by the bytes per value to see what you asked for, then ask for less: float32 instead of float64, chunks, np.memmap or a sparse matrix. If the shape is (n, n) for your row count, an algorithm is building a pairwise matrix, and a chunked version is the fix.

Why do I get MemoryError when I have enough RAM?

The limit isn't RAM. It can be a 32-bit Python's 2 GB of address space, the Windows commit limit, a container's memory cap, or Linux's strict overcommit mode. The size in the message is also one request on top of everything the process already holds.

How much memory does a NumPy array use?

Its number of elements times the item size: a.nbytes, or the product of the shape times 8 for float64, 4 for float32 and 1 for int8. A 10,000 × 10,000 float64 array is 800 million bytes, which NumPy prints as 763 MiB.

Can I catch MemoryError with try and except?

Yes, it is an ordinary exception, and our 1 PiB request was caught and the process carried on. But on Linux a process that runs out after the allocation succeeded is killed, and there is nothing to catch.

Does 64-bit Python fix MemoryError?

Only when the limit was a 32-bit Python's address space. On a 64-bit Python the limit is real memory, the commit limit or a cap, and the fixes are a smaller dtype, chunks or a bigger machine.

Sources

Read and run on 2 December 2026. Our script ran on Windows 11 (Python 3.14.3, NumPy 2.5.5, SciPy 1.18.1, 64 GB of RAM) and in Docker's python:3.14-slim with --memory 512m --memory-swap 512m.


Try Fastero free: run your notebooks next to your team's data, and on Pro rent 8 to 32 GB by the hour when the arithmetic says you need it. No credit card required.

Ready to try it yourself?

Connect your database, ask questions in plain English, and get live dashboards — in under 2 minutes. No credit card required.

Follow Fastero on LinkedIn for new articles and examples.

Keep reading

Related articles