Write Python. Understand every error.

Open the editor

Error guide · NumPy errors

ValueError: operands could not be broadcast together

NumPy cannot combine two arrays because their shapes do not fit together.

Example

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30, 40])
print(a + b)

What Python says

ValueError: operands could not be broadcast together with shapes (3,) (4,)

As printed by Python 3.12. Other versions may word it slightly differently.

Try this code in Py-CRAFT

Why it happens

NumPy does arithmetic on matching elements. When the shapes differ, it tries to stretch the smaller array (this is called broadcasting), but that works only when the sizes are equal or one of them is 1. An array of 3 values and an array of 4 values cannot be matched, and the message lists both shapes.

How to fix it

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)

Output: [11 22 33]

Tips

Learn the ideas behind it

Other common errors

Share this page: