np.sort() always returns a brand-new sorted array, while calling .sort() as a method directly on an array sorts it in place and returns None — the same distinction as Python's sorted() versus list.sort(). For a multi-dimensional array, np.sort() sorts along the last axis by default, sorting each row independently rather than sorting the whole array as one flattened sequence; pass axis=None to sort a fully flattened copy instead.
1Understanding np.sort()
np.sort() always returns a brand-new sorted array, while calling .sort() as a method directly on an array sorts it in place and returns None — the same distinction as Python's sorted() versus list.sort(). For a multi-dimensional array, np.sort() sorts along the last axis by default, sorting each row independently rather than sorting the whole array as one flattened sequence; pass axis=None to sort a fully flattened copy instead.
np.sort(), which returns a new array, and arr.sort(), which sorts in place and returns None, are easy to confuse — the same distinction as Python's sorted() versus list.sort() — pick np.sort() when you need to keep the original array's order intact.
import numpy as np
arr = np.array([3, 1, 4, 1, 5, 9])
sorted_arr = np.sort(arr)
print(sorted_arr)
print(arr)2Practical Example
Here is a real-world application of np.sort() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[3, 1, 2], [6, 5, 4]])
print(np.sort(matrix, axis=1))3Best Practices
Follow these guidelines when working with np.sort():
1. Use np.sort() when the original array's order needs to be preserved; use arr.sort() only when in-place mutation is actually intended
2. Specify axis explicitly for multi-dimensional arrays, since the default sorts each row independently along the last axis, not the whole flattened array
3. Use np.argsort() instead of np.sort() when you need the sorted order as indices to apply to other related arrays, not just the sorted values themselves
Tip: np.sort(), which returns a new array, and arr.sort(), which sorts in place and returns None, are easy to confuse — the same distinction as Python's sorted() versus list.sort() — pick np.sort() when you need to keep the original array's order intact.
import numpy as np
arr = np.array([3, 1, 4, 1, 5, 9])
sorted_arr = np.sort(arr)
print(sorted_arr)
print(arr)