All sample questions / NumPy
What does print((a + b).tolist()) print? NumPy Broadcasting and Shapes
Block 3, Broadcasting and Shapes, question 7 of the NumPy sample
import numpy as np
a = np.arange(3)[:, np.newaxis]
b = np.arange(4)[np.newaxis, :]
print((a + b).tolist())
What does this print?
Show the answer and why each option is right or wrong
Answer, B. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
- A. [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
- Ignores the contribution of a entirely and repeats b unchanged on every row.
- B. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
- Correct. Each row i adds the constant a value i to every entry of b, so row 0 is b itself, row 1 is b plus 1, and row 2 is b plus 2.
- C. [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2]]
- Ignores the contribution of b entirely and repeats each value of a across a whole row.
- D. [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
- Transposes the grid, producing 4 rows of length 3 instead of 3 rows of length 4.
Broadcasting a column against a row builds a grid where every cell is the sum of that row's value from the column operand and that column's value from the row operand. Neither operand ever gets dropped from the result, both contribute to every single cell.
The answer above is what NumPy 2.4.4 printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 279 NumPy interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 279 NumPy questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free NumPy sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.