All sample questions / NumPy

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

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

import numpy as np
h = np.array([[1, 2], [3, 4]])
print(h.cumsum(axis=1).tolist())

What does this print?

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

Answer, D. [[1, 3], [3, 7]]

A. [[1, 2], [4, 6]]
Accumulates down each column instead, the result for axis=0 on the same array.
B. [1, 3, 6, 10]
Flattens the array first, the result cumsum would give without any axis at all.
C. [[1, 2], [3, 4]]
Assumes cumsum leaves the array unchanged when an axis is given.
D. [[1, 3], [3, 7]]
Correct. axis=1 accumulates across each row, so the first row becomes 1 and 1+2, and the second row becomes 3 and 3+4.

cumsum(axis=1) resets its running total at the start of every row and walks left to right within that row only. Rows never influence each other under this axis, unlike axis=0 where columns accumulate independently of each other.

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.