Learning Objectives – after this chapter you will be able to:
  • Sort numbers, strings and booleans with np.sort().
  • Distinguish np.sort() (returns a copy) from arr.sort() (in place).
  • Sort 2-D arrays along rows or columns and in descending order.
  • Use argsort() to sort one array by another.
Sorting Arrays

Sorting arranges elements in an ordered sequence – numeric or alphabetical, ascending or descending. np.sort(arr) returns a sorted copy and leaves the original unchanged.

import numpy as np

nums = np.array([42, 7, 19, 3, 25])
print(np.sort(nums))
print(nums)                                   # unchanged

names = np.array(["mango", "apple", "kiwi", "banana"])
print(np.sort(names))                         # alphabetical

flags = np.array([True, False, True, False])
print(np.sort(flags))                         # False before True
Output
[ 3  7 19 25 42]
[42  7 19  3 25]
['apple' 'banana' 'kiwi' 'mango']
[False False  True  True]
In-place Sorting: arr.sort()
import numpy as np

nums = np.array([42, 7, 19, 3, 25])
result = nums.sort()       # sorts the array itself
print(nums)
print(result)              # returns None
Output
[ 3  7 19 25 42]
None
Descending Order

NumPy has no reverse=True option. Sort ascending and reverse with [::-1] (or sort the negated numbers).

import numpy as np

nums = np.array([42, 7, 19, 3, 25])
print(np.sort(nums)[::-1])
print(-np.sort(-nums))
Output
[42 25 19  7  3]
[42 25 19  7  3]
Sorting 2-D Arrays

By default np.sort() sorts along the last axis – each row separately. Use axis=0 to sort each column, and axis=None to flatten and sort everything.

import numpy as np

m = np.array([[9, 2, 7],
              [4, 8, 1]])
print(np.sort(m))             # each row
print(np.sort(m, axis=0))     # each column
print(np.sort(m, axis=None))  # all values
Output
[[2 7 9]
 [1 4 8]]
[[4 2 1]
 [9 8 7]]
[1 2 4 7 8 9]
argsort(): Indexes that Would Sort

argsort() returns the indexes that would sort the array. It is used to sort one array according to the values of another.

import numpy as np

students = np.array(["Asha", "Ravi", "Meera", "John"])
marks = np.array([82, 67, 91, 74])

order = marks.argsort()
print(order)
print(students[order])                 # lowest to highest
print(students[order[::-1]][:2])       # top two
Output
[1 3 0 2]
['Ravi' 'John' 'Asha' 'Meera']
['Meera' 'Asha']
Key Takeaways
  • np.sort() returns a sorted copy; arr.sort() sorts in place and returns None.
  • Default axis is the last one (rows of a 2-D array); use [::-1] for descending order.
  • argsort() gives the sorting order to rearrange related arrays.
Video : Array Sort
Question / Answer (15 questions)

Answer : Sorting is arranging elements in an ordered sequence – numerically or alphabetically, in ascending or descending order.

Answer : No. np.sort(arr) returns a new sorted copy and leaves the original unchanged.

Answer : np.sort(arr) returns a sorted copy and keeps the original. arr.sort() sorts the array in place, changing it, and returns None.

Answer : Alphabetically (lexicographically, by character code). For ["mango", "apple", "kiwi", "banana"] the result is ['apple' 'banana' 'kiwi' 'mango'].

Answer : False is treated as 0 and True as 1, so all False values come before True values.

Answer : NumPy sorts only in ascending order, so reverse the result: np.sort(arr)[::-1]. For numbers, -np.sort(-arr) also works.

Answer : Along the last axis (axis=-1), so each row is sorted independently.

Answer : Use axis=0: np.sort(m, axis=0).

Answer : It flattens the array and returns all values sorted in a single 1-D array.

Answer : It returns the indexes that would sort the array. For marks [82, 67, 91, 74] it returns [1 3 0 2].

Answer : Compute order = marks.argsort() and index the names with it: names[order]. Use order[::-1] for highest marks first.

Answer : students[marks.argsort()[::-1][:2]] – reverse the ascending order to descending and take the first two.

Answer : [[2 7 9] [1 4 8]] – each row is sorted separately.

Answer : Yes, with the kind argument, e.g. np.sort(arr, kind="stable") or kind="mergesort". "stable" keeps equal elements in their original order. The default is "quicksort" (implemented as an introsort).

Answer : To rank values (e.g. top scorers), find medians and percentiles, prepare data for binary search (searchsorted) and present results in a meaningful order.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What does arr.sort() return?

Show Answer

Correct Answer : C. None
In-place sort returns None.

Q2. np.sort(np.array([True, False, True])) gives:

Show Answer

Correct Answer : A. [False True True]
False (0) sorts before True (1).

Q3. Which expression sorts an array in descending order?

Show Answer

Correct Answer : B. np.sort(arr)[::-1]
NumPy has no reverse option; reverse the sorted result.

Q4. np.array([30, 10, 20]).argsort() returns:

Show Answer

Correct Answer : D. [1 2 0]
The smallest (10) is at index 1, then 20 at index 2, then 30 at index 0.

Q5. To sort every COLUMN of a 2-D array you use:

Show Answer

Correct Answer : A. axis=0
axis=0 sorts down each column.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. NumPy Developers. (n.d.). Sorting, searching, and counting. NumPy API Reference. https://numpy.org/doc/stable/reference/routines.sort.html
  2. NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
  3. NumPy Developers. (n.d.). NumPy: the absolute basics for beginners. NumPy User Guide. https://numpy.org/doc/stable/user/absolute_beginners.html
  4. VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/