NumPy Broadcasting Deep Dive

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)

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. np.newaxis = Add Dimension

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

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

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