Python / Data Science Essentials Interview Questions
What is NumPy broadcasting and how does it work?
Broadcasting is the set of rules NumPy uses to perform element-wise operations on arrays of different but compatible shapes, without physically copying data to make them the same size. It is one of the most powerful and often misunderstood NumPy features.
The rules, applied dimension by dimension starting from the trailing (rightmost) axis:
- If the arrays have different numbers of dimensions, prepend 1s to the shape of the smaller-dimensional array.
- Dimensions of size 1 are stretched to match the other array's size in that dimension.
- If any dimension neither matches nor is 1, a
ValueErroris raised.
import numpy as np
# Scalar broadcast over array
a = np.array([1, 2, 3])
print(a * 10) # [10 20 30]
# (3,) and (3, 1) — column vector subtraction from each column
matrix = np.array([[10, 20, 30],
[40, 50, 60]])
row_min = matrix.min(axis=1, keepdims=True) # shape (2, 1)
normalised = matrix - row_min # broadcasts: (2,3) - (2,1) -> (2,3)
print(normalised)
# [[ 0 10 20]
# [ 0 10 20]]
# Outer product via broadcasting
col = np.array([[1], [2], [3]]) # shape (3, 1)
row = np.array([10, 20, 30]) # shape (3,) -> treated as (1, 3)
print(col * row)
# [[10 20 30]
# [20 40 60]
# [30 60 90]]Broadcasting avoids the memory cost of explicit np.tile or np.repeat calls. The stretched values are never physically written — NumPy just iterates as if they were. For large arrays this can mean the difference between fitting in RAM and running out of memory.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
