Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
a.sort, sorted(a), np_argsort(a) and np.lexsort(b, a) in Python
Python provides built-in sorting functions (sorted(), list.sort()) and NumPy provides advanced sorting (np.argsort(), np.lexsort()) for working with arrays and multiple sort keys.
sorted()
Returns a new sorted list without modifying the original ?
a = [9, 5, 3, 1, 12, 6]
b = sorted(a)
print("Sorted Array:", b)
print("Original Array:", a)
Sorted Array: [1, 3, 5, 6, 9, 12] Original Array: [9, 5, 3, 1, 12, 6]
list.sort()
Sorts the list in-place (modifies the original, returns None). Faster than sorted() since it doesn't create a copy ?
a = [9, 5, 3, 1, 12, 6]
print("Original Array:", a)
a.sort()
print("Sorted Array:", a)
Original Array: [9, 5, 3, 1, 12, 6] Sorted Array: [1, 3, 5, 6, 9, 12]
numpy.argsort()
Returns the indices that would sort the array, not the sorted values themselves. Useful when you need to track original positions ?
import numpy as np
x = np.array([9, 5, 3, 1, 12, 6])
print("Array:", x)
# Print index-value pairs
for i in range(len(x)):
print(f" [{i}] = {x[i]}")
# Get indices of sorted elements
s = np.argsort(x)
print("Sorted indices:", s)
print("Sorted values:", x[s])
Array: [ 9 5 3 1 12 6] [0] = 9 [1] = 5 [2] = 3 [3] = 1 [4] = 12 [5] = 6 Sorted indices: [3 2 1 5 0 4] Sorted values: [ 1 3 5 6 9 12]
Index 3 (value 1) comes first, then index 2 (value 3), and so on.
numpy.lexsort()
Sorts using multiple keys (like sorting a spreadsheet by column A, then by column B for ties). The last key in the argument is the primary sort key ?
import numpy as np
colA = [2, 5, 1, 8, 1] # Primary sort key
colB = [9, 0, 3, 2, 0] # Secondary sort key
# Sort by colA first, then colB for ties
sorted_index = np.lexsort((colB, colA))
print("Sorted indices:", sorted_index)
print("Sorted pairs:", [(colA[i], colB[i]) for i in sorted_index])
Sorted indices: [4 2 0 1 3] Sorted pairs: [(1, 0), (1, 3), (2, 9), (5, 0), (8, 2)]
ColA has two values of 1 at indices 2 and 4. Since colB[4]=0 < colB[2]=3, index 4 comes before index 2 in the result.
Comparison
| Function | Returns | Modifies Original? | Use Case |
|---|---|---|---|
sorted(a) |
New sorted list | No | General sorting, keep original |
a.sort() |
None (in-place) | Yes | Memory-efficient sorting |
np.argsort(a) |
Sorted indices | No | Track original positions |
np.lexsort(keys) |
Sorted indices | No | Multi-column sorting |
Conclusion
Use sorted() when you need a new sorted list and list.sort() for in-place sorting. For NumPy arrays, np.argsort() returns sorted indices to track positions, and np.lexsort() handles multi-key sorting where the last argument is the primary key.
