- Home
- Interview Questions
- Python
- What is broadcasting in NumPy and what rules decide whether …
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: Broadcasting is how NumPy performs element-wise operations on arrays of different shapes without copying data. Shapes are compared from the last dimension backwards, and two dimensions are compatible only if they are equal or one of them is 1. A missing dimension is treated as 1.
Detailed explanation
Element-wise operations like +, * or > need operands of matching shape. Broadcasting relaxes this. NumPy behaves as if the smaller array were stretched to match the larger one. It does not actually build that stretched array in memory. Internally it reuses the same values by setting a stride of zero along the stretched axis.
NumPy applies these rules to the two shapes:
- Align from the right. Write the shapes one under the other, right-aligned. If one array has fewer dimensions, pad its shape on the left with 1s.
- Compare each dimension. Two sizes are compatible if they are equal, or if one of them is 1.
- Stretch the 1s. Any dimension of size 1 is repeated to match the other array's size along that axis.
- Otherwise fail. If any pair is neither equal nor 1, NumPy raises
ValueError: operands could not be broadcast together.
The result shape is the maximum size in each dimension. Some worked cases:
| Shape A | Shape B | Result |
|---|---|---|
| (3, 4) | (4,) | (3, 4) |
| (3, 4) | (3,) | Error: 4 vs 3 |
| (3, 4) | (3, 1) | (3, 4) |
| (3, 1) | (1, 5) | (3, 5) |
| (2, 1, 4) | (3, 1) | (2, 3, 4) |
Broadcasting matters for two reasons. It keeps code vectorised, so the loop runs in compiled C instead of Python. It also avoids allocating repeated copies of the smaller array. The output array is still full size, though. Broadcasting a (10000, 1) array against a (1, 10000) array produces 100 million elements.
Example
import numpy as np
a = np.arange(12).reshape(3, 4) # shape (3, 4)
row = np.array([10, 20, 30, 40]) # shape (4,)
print(a + row) # row added to every row of a
col = np.array([1, 2, 3]) # shape (3,)
# a + col -> ValueError: shapes (3,4) (3,)
print(a + col[:, np.newaxis]) # col is now (3, 1), works
# Standardise each column (mean over axis 0 has shape (4,))
z = (a - a.mean(axis=0)) / a.std(axis=0)
# Centre each row: keepdims keeps shape (3, 1) instead of (3,)
centered = a - a.mean(axis=1, keepdims=True)
# Outer-style comparison: (3, 1) vs (1, 4) gives (3, 4)
mask = col[:, None] > np.array([0, 1, 2, 3])[None, :]The row mean case shows the most common trap. a.mean(axis=1) has shape (3,). Against (3, 4) it aligns with the last axis of size 4 and fails. Using keepdims=True or reshaping to (3, 1) fixes it.
Common mistakes
- Assuming NumPy aligns shapes from the left. It always aligns from the trailing dimension, so a (3,) array pairs with the columns of a (3, 3) matrix, not the rows.
- Forgetting
keepdims=Trueafter a reduction along axis 1. The result is then silently subtracted along the wrong axis when the matrix is square, because the shapes still match. - Thinking broadcasting saves memory in the output. It only avoids copying the inputs. An accidental (n, 1) by (1, n) operation can exhaust RAM.
- Mixing up shape (n,) and (n, 1). They are different. A 1-D array is not a column vector.
Follow-up questions
- How does
np.newaxis(orNone) differ fromreshapewhen preparing arrays for broadcasting? - How would you compute pairwise Euclidean distances between two sets of points using broadcasting?
- What does
np.broadcast_toreturn, and why is its result read-only?
Interview tip: Write both shapes right-aligned on the whiteboard and check them column by column. Interviewers want to see you apply the rule, not guess.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More medium Python questions
Related Questions
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
- What is the difference between assignment, shallow copy and deep copy in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)