Broadcasting (NumPy)

Broadcasting is NumPy's set of rules for combining arrays of different shapes in an operation by automatically stretching the smaller one across the larger, without actually copying data. It is what lets you add a scalar or a row to a whole matrix.

NumPy

When you write array + 10, NumPy broadcasts the scalar 10 across every element. The same logic extends to arrays: a (3, 1) column and a (1, 3) row broadcast together into a (3, 3) result. The rule is that NumPy compares shapes from the trailing dimension backward, and dimensions are compatible when they are equal or one of them is 1.

Broadcasting is both a convenience and a performance win: it avoids materializing the stretched copies in memory and runs the operation in one fast vectorized pass. Subtracting a per-column mean from a data matrix, or scaling rows by a vector of weights, are everyday examples.

When shapes don't line up under these rules NumPy raises a 'could not be broadcast together' error; reshaping one operand or inserting a length-1 axis with np.newaxis usually fixes it.

Syntax

small_array OP large_array  # shapes aligned by broadcasting rules

Examples

Python

import numpy as np
col = np.array([[1], [2], [3]])
row = np.array([10, 20, 30])
print(col + row)

Output:

[[11 21 31]
 [12 22 32]
 [13 23 33]]

Learn it in a lesson

See also

Back to the Dictionary