Skip to content

/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

bash
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

bash
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

bash
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