NumPy Broadcasting

Last Updated: 09 Nov 2025


Broadcasting allows NumPy to automatically expand arrays of different shapes during arithmetic — no copying, no loops.

Hinglish Tip: “Broadcasting = chhoti array ko bada bana do — bina memory waste kiye!”


The 3 Golden Rules

  • Pad smaller shape with 1s on the left
  • Compare dimensions from the right
  • Compatible if: same size or one is 1
# (3, 2) + (2,) → pad → (1, 2)
# Compare: 2==2, 3!=1 → OK → result (3, 2)

# (3,1,5) + (3,5) → pad → (1,3,5)
# Compare: 3==3, 1==3 → OK → result (3,3,5)

# (3,2) + (3,) → pad → (1,3,2)
# Compare: 2!=3, 3==3 → Fail to broadcast

1. Scalar + Array (Easiest)

import numpy as np

arr = np.array([10, 20, 30])
print(arr + 5)     # [15 25 35]
print(arr * 2.5)   # [25. 50. 75.]

2. 1D + 2D (Row/Column Wise)

Column-wise (most common)

data = np.array([[100, 200, 300],
                 [400, 500, 600]])   # (2, 3)

bias = np.array([10, 20, 30])        # (3,)
print(data + bias)
# [[110 220 330]
#  [410 520 630]]

Row-wise → use np.newaxis

row_bias = np.array([100, 200])[:, np.newaxis]  # (2, 1)
print(data + row_bias)
# [[200 300 400]
#  [600 700 800]]

3. 2D + 2D (Grid Operations)

grid = np.array([[1, 2],
                 [3, 4]])     # (2, 2)

pattern = np.array([[10],
                    [20]])       # (2, 1)

print(grid * pattern)
# [[10  20]
#  [60  80]]

4. Add Dimension

  • Use np.newaxis or None to add a dimension to an array.
  • It helps to make a shape(1,col) or (row,1) array.
x = np.array([10, 20, 30, 40])      # shape (4,)
print(x.shape)                      # (4,)

# Make it a column vector  → (4, 1)
col = x[:, np.newaxis]              # or x[:, None]
print(col.shape)                    # (4, 1)
print(col)

vec = np.array([1, 2, 3])           # (3,)

# Make row vector
row = vec[np.newaxis, :]
print(row.shape)                    # (1, 3)
print(row)