All sample questions / NumPy

What does print(np.sort(a, axis=1).tolist()) print? NumPy Sorting, Searching and unique

Block 7, Sorting, Searching and unique, question 17 of the NumPy sample

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

What does this print?

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

Answer, A. [[1, 3], [2, 4]]

A. [[1, 3], [2, 4]]
Correct. axis=1 sorts each row independently across its columns, so 3, 1 becomes 1, 3 and 2, 4 stays 2, 4.
B. [[2, 1], [3, 4]]
Sorts along the columns instead of the rows, the result axis=0 would actually give.
C. [[3, 1], [4, 2]]
Sorts each row in descending order instead of the default ascending order.
D. [[1, 2], [3, 4]]
Assumes the whole array gets flattened, sorted, and reshaped back, ignoring the axis argument entirely.

axis=1 on a 2D array sorts independently within each row, rearranging only the values that share a row. The default axis for np.sort on a multi dimensional array is the last one, which for a 2D array is exactly this row wise behavior.

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.