Python
NumPy
ValueError
Broadcasting
Array Shapes

python numpy ValueError operands could not be broadcast together with shapes

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The NumPy broadcasting error means you asked NumPy to perform an elementwise operation on arrays whose shapes cannot be aligned under the broadcasting rules. The fix is usually to inspect the shapes, understand which axis should expand, and then reshape, transpose, or change the operation so the arrays are genuinely compatible.

What Broadcasting Tries to Do

Broadcasting lets NumPy apply elementwise operations to arrays of different shapes when the dimensions are compatible. NumPy compares shapes from the rightmost dimension backward. Two dimensions are compatible if they are equal or if one of them is 1.

python
1import numpy as np
2
3a = np.array([[1, 2, 3], [4, 5, 6]])      # shape (2, 3)
4b = np.array([10, 20, 30])                 # shape (3,)
5
6print(a + b)

This works because b can be treated like shape (1, 3) and then broadcast across the rows of a.

Why the Error Happens

Now consider an incompatible case.

python
1import numpy as np
2
3a = np.ones((2, 3))
4b = np.ones((2, 2))
5
6print(a + b)

NumPy raises:

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

The last dimensions are 3 and 2, and neither is 1, so broadcasting cannot align them.

First Step: Print the Shapes

The fastest debugging step is simply to check the shapes right before the failing operation.

python
print(a.shape)
print(b.shape)

Many broadcasting bugs come from an earlier preprocessing step that produced (n, 1) instead of (n,), or swapped rows and columns unexpectedly.

Fix 1: Reshape the Smaller Array Correctly

If your intent is to expand one dimension, reshape explicitly.

python
1import numpy as np
2
3a = np.array([[1, 2, 3], [4, 5, 6]])      # shape (2, 3)
4b = np.array([[10], [20]])                # shape (2, 1)
5
6print(a + b)

This works because (2, 1) can broadcast across the columns to match (2, 3).

Fix 2: Add a New Axis

Sometimes you have a one-dimensional array that needs to become a column vector.

python
1import numpy as np
2
3x = np.array([1, 2])
4y = np.array([[10, 20, 30], [40, 50, 60]])
5
6result = x[:, np.newaxis] + y
7print(result)

x[:, np.newaxis] changes shape from (2,) to (2, 1), which often fixes row-versus-column alignment issues.

Fix 3: Transpose if Axes Are Reversed

Sometimes the data is already correct but the axes are flipped.

python
1import numpy as np
2
3a = np.ones((3, 2))
4b = np.array([10, 20])
5
6print(a + b)

This works because the last dimension matches 2. If your array had shape (2, 3) when you meant (3, 2), a transpose might be the real fix rather than forcing a reshape.

Do Not Confuse Elementwise Multiply with Matrix Multiply

This error often appears when people expected matrix multiplication but wrote *.

python
1import numpy as np
2
3A = np.ones((2, 3))
4B = np.ones((3, 2))
5
6# Elementwise multiply fails here.
7# print(A * B)
8
9print(A @ B)

Use @ or np.matmul for matrix multiplication. Broadcasting rules apply to elementwise operations, not to linear algebra semantics.

Common Pitfalls

A common mistake is assuming arrays with the same total number of elements can always be combined. Broadcasting only cares about compatible dimensions, not total size. Another is forgetting that a row vector of shape (3,) behaves differently from a column vector of shape (3, 1). Developers also often debug the failing line instead of printing the shapes produced by the earlier data pipeline steps that created the mismatch.

Summary

  • Broadcasting compares shapes from the trailing dimensions backward.
  • Dimensions must match or one of them must be 1.
  • Print shapes first before trying random reshapes.
  • Use reshape, np.newaxis, or transpose when the alignment intent is clear.
  • If you meant matrix multiplication, use @, not *.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.