Broadcasting allows operations between arrays of different shapes by automatically expanding dimensions.
import numpy as np
# Scalar broadcast to array
a = np.array([[1, 2, 3], [4, 5, 6]])
a + 10 # adds 10 to every element
# 1D array broadcast to 2D
row = np.array([1, 2, 3]) # shape (3,)
a + row # adds row to each row of a
# Column vector broadcast
col = np.array([[10], [20]]) # shape (2,1)
a + col # adds 10 to row 0, 20 to row 1
# Rules:
# 1. Shapes compared right to left
# 2. Dimensions must match or be 1
# 3. Size-1 dimensions are stretched to match