All sample questions / NumPy

What does print(a.sum(axis=1).tolist()) print? NumPy Reductions and the axis Argument

Block 5, Reductions and the axis Argument, question 11 of the NumPy sample

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.sum(axis=1).tolist())

What does this print?

  1. A. [6, 15]
  2. B. 21
  3. C. [3, 6]
  4. D. [5, 7, 9]
Show the answer and why each option is right or wrong

Answer, A. [6, 15]

A. [6, 15]
Correct. axis=1 collapses the columns and adds across each row, giving 1+2+3 for the first row and 4+5+6 for the second.
B. 21
Collapses the whole array into one grand total instead of one sum per row.
C. [3, 6]
Keeps only the last entry of each row rather than adding the whole row.
D. [5, 7, 9]
Sums down each column instead, the result for axis=0 on the same array.

Reducing along axis=1 keeps one result per row and drops the column axis entirely. It is easy to swap axis=0 and axis=1 in your head, the safest check is to look at how many numbers come out, one per row means axis=1.

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.