Q&A library Python

What is broadcasting in NumPy?

Python Intermediate arraysbroadcastingnumpy

Short answer

Broadcasting lets NumPy apply an operation between arrays of different shapes by stretching the smaller one across the larger, without copying data. It powers concise, fast array maths but follows strict shape rules.

The short version

Broadcasting is how NumPy applies an operation between arrays of different shapes. It stretches the smaller array across the larger one so their shapes line up, without actually copying the data. This is what lets you add a single number, or a one-dimensional row, to a whole two-dimensional array in one expression.

The simplest case

Adding a scalar applies it to every element.

import numpy as np

grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid * 2)
[[ 2  4  6]
 [ 8 10 12]]

The single value 2 is broadcast across every element, so you do not write a loop.

Stretching a row across rows

A one-dimensional array can be applied to each row of a two-dimensional one, provided the lengths match.

offsets = np.array([10, 20, 30])
print(grid + offsets)
[[11 22 33]
 [14 25 36]]

Here offsets has shape (3,) and grid has shape (2, 3). NumPy stretches offsets down the two rows, adding 10, 20, 30 across the columns of each.

The shape rules

NumPy compares shapes from the last dimension backwards. Two dimensions are compatible when they are equal, or one of them is 1. If neither holds, you get a ValueError about shapes not being broadcastable. So a (2, 3) array works with a (3,) or a (2, 1) array, but not with a (2,) array, which is the mistake that most often trips people up.

The common error

wrong = np.array([10, 20])          # shape (2,)
grid + wrong                        # ValueError: shapes not aligned

You meant to add one value per row, but a (2,) array lines up with the columns, not the rows, and 2 does not match the 3 columns. Reshape it to a column first.

grid + wrong.reshape(2, 1)          # now it stretches across columns

Why it matters

Broadcasting is not just convenience; it avoids building large intermediate arrays and runs in fast compiled code, so it is central to writing NumPy that is both short and quick. When an operation fails with a shape error, print the .shape of each array and check it against the rules above, because the shapes almost always reveal the problem at once.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project