All sample questions / NumPy

What does print(r, a.tolist()) print? NumPy Sorting, Searching and unique

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

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

What does this print?

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

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

A. None [1, 2, 3]
Correct. The in place method a.sort() reorders the array itself and returns None, so printing its result shows None while a itself now holds the sorted values.
B. None [3, 1, 2]
Assumes a.sort() returns None without actually reordering the array in place.
C. [1, 2, 3] [1, 2, 3]
Assumes a.sort() returns the sorted array the way np.sort would, instead of returning None.
D. array([1, 2, 3]) [1, 2, 3]
Assumes the in place method hands back a printed array object rather than the plain value None.

a.sort() is an in place method, it reorders the array itself and returns None, exactly like list.sort() in plain Python. Only the free function np.sort returns a new sorted array that can be captured in a variable.

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.