1. Home
  2. Interview Questions
  3. Python
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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:

  1. 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.
  2. Compare each dimension. Two sizes are compatible if they are equal, or if one of them is 1.
  3. Stretch the 1s. Any dimension of size 1 is repeated to match the other array's size along that axis.
  4. 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 AShape BResult
(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=True after 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 (or None) differ from reshape when preparing arrays for broadcasting?
  • How would you compute pairwise Euclidean distances between two sets of points using broadcasting?
  • What does np.broadcast_to return, 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

All medium questions →

Related Questions

‹
Q8 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA