All sample questions / NumPy

What does print(np.split(a, 3)) print? NumPy Stacking, Splitting and Concatenation

Block 8, Stacking, Splitting and Concatenation, question 19 of the NumPy sample

import numpy as np
a = np.arange(9)
print(np.split(a, 3))

What does this print?

  1. A. [array([0, 1, 2]), array([3, 4, 5])]
  2. B. [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
  3. C. [array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])]
  4. D. [array([0, 1, 2, 3, 4, 5, 6, 7, 8])]
Show the answer and why each option is right or wrong

Answer, B. [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

A. [array([0, 1, 2]), array([3, 4, 5])]
Drops one of the three expected pieces from the result.
B. [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
Correct. split with an integer count of 3 cuts the nine values into three equal, contiguous chunks in order, and it returns a plain Python list of the resulting arrays.
C. [array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])]
Assumes split distributes the values round robin across the pieces instead of keeping each chunk contiguous.
D. [array([0, 1, 2, 3, 4, 5, 6, 7, 8])]
Assumes split with a count argument returns the array untouched inside a single element list.

np.split with an integer divides the array into that many equal, contiguous pieces along the given axis, always returning a plain list of arrays rather than a single array. It only works when the axis length divides evenly by that integer, otherwise it raises instead of guessing a chunk size.

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.