Labs ICT
Pro Login

Broadcasting

How NumPy handles operations on different shaped arrays.

Broadcasting

Broadcasting is like magic - it lets you operate on arrays of different shapes. Think of it like a teacher automatically making copies of worksheets for all students.

Scalar + Array

The simplest case: a scalar broadcasts to match the array shape.


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
result = arr + 10

print(f"Original:\n{arr}")
print(f"Plus 10:\n{result}")
    

The scalar 10 gets broadcast to a 2x3 array of 10s. No extra memory needed!

Different Shapes

NumPy automatically broadcasts when shapes are compatible.


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
row = np.array([10, 20, 30])

result = arr + row
print(f"Matrix:\n{arr}")
print(f"Row: {row}")
print(f"Result:\n{result}")
    

Here is the thing - the row array gets broadcast to match the matrix shape. Each row of the matrix adds the same row vector.

Broadcasting Rules

NumPy compares shapes from right to left. Dimensions must be equal or one of them must be 1.


import numpy as np

a = np.array([[1], [2], [3]])
b = np.array([10, 20, 30])

result = a + b
print(f"Column vector:\n{a}")
print(f"Row vector: {b}")
print(f"Result:\n{result}")
    

One thing that confused me at first was why sometimes broadcasting fails. It happens when dimensions aren't compatible and neither is 1.

Try it Yourself →

Key Takeaways

  • Broadcasting lets you operate on different-shaped arrays
  • Scalars broadcast to match array dimensions
  • Dimensions must be equal or one must be 1
  • Comparison happens from right to left