All sample questions / NumPy

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

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

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

What does this print?

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

Answer, B. [[0, 1], [1, 0]]

A. [[1, 0], [1, 0]]
Repeats the second row twice for pattern reasons, instead of noticing the first row was already in order.
B. [[0, 1], [1, 0]]
Correct. argsort with axis=1 works row by row, and the first row is already ascending so its indices stay 0, 1, while the second row needs its two entries swapped, giving indices 1, 0.
C. [[0, 1], [0, 1]]
Assumes both rows produce the same index order, ignoring that the second row is not already sorted.
D. [[1, 0], [0, 1]]
Swaps the two rows of the result, giving the second row the indices that belong to the first.

argsort with an explicit axis works independently along that axis, exactly like np.sort does, row by row when axis=1. A row that is already in ascending order simply returns its original positions unchanged.

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.