/errors/numpy/operands-could-not-be-broadcast
ValueError: operands could not be broadcast together with shapes
verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
- tool
- NumPy
- exit code
- 1
- versions
- NumPy 1.x, NumPy 2.x
- os
- any
NumPy raises ValueError: operands could not be broadcast together with shapes (3,) (4,) when it cannot stretch two arrays to a common shape. Broadcasting compares the shapes from the last dimension backwards; each pair of sizes must be equal, or one of them must be 1.
Reproduce the error
python -c '
import numpy as np
try:
np.array([1, 2, 3]) + np.array([1, 2, 3, 4])
except ValueError as e:
print("ValueError:", e)'Output
ValueError: operands could not be broadcast together with shapes (3,) (4,)
The rule, with shapes that work and shapes that do not
python -c '
import numpy as np
cases = [((3, 4), (4,)), ((3, 4), (3,)), ((3, 4), (3, 1)), ((2, 1, 5), (3, 1)), ((5,), (1,))]
for a, b in cases:
try:
r = (np.ones(a) + np.ones(b)).shape
except ValueError:
r = "error"
print(a, "+", b, "->", r)'Output
(3, 4) + (4,) -> (3, 4) (3, 4) + (3,) -> error (3, 4) + (3, 1) -> (3, 4) (2, 1, 5) + (3, 1) -> (2, 3, 5) (5,) + (1,) -> (5,)
(3, 4) and (3,) fail because the last dimensions are 4 and 3. Reshaping the second operand to (3, 1) makes it broadcast along the columns.
Fix: add the missing axis
python -c '
import numpy as np
m = np.arange(12).reshape(3, 4)
row_means = m.mean(axis=1) # shape (3,)
print((m - row_means[:, np.newaxis]).shape)
print((m - m.mean(axis=1, keepdims=True)).shape)'Output
(3, 4) (3, 4)
keepdims=True keeps the reduced axis with size 1, which is usually the cleanest fix after a reduction.
Sources
Related pages
errors · pytorchtorch.OutOfMemoryError: CUDA out of memory. Tried to allocate …PyTorch raises CUDA out of memory when the GPU cannot fit the next allocation. Lower the batch size, use mixed precision, drop references, reduce fragmentation.cheat sheets · pandaspandas cheat sheet: read, select, filter, group and reshapepandas cheat sheet: read CSV and Parquet, select with loc and iloc, filter rows, add columns, group and aggregate, pivot, handle missing values and write files.compat · numpyNumPy versions and supported Python versions (2.0 to 2.5)Python versions supported by each NumPy release: 2.0 runs on 3.9-3.12, 2.1 and 2.2 on 3.10-3.13, 2.4 on 3.11-3.14 and 2.5 on 3.12-3.14, per the release notes.