searchsorted() assumes its first argument is already sorted, and uses an efficient binary search, O(log n), rather than a linear scan, to find the insertion point for each value in values — it does not check or enforce that the array is actually sorted, so passing an unsorted array silently produces meaningless results. The side parameter controls tie-breaking when a value already exists in the array: 'left', the default, inserts before any existing equal elements, while 'right' inserts after them.
1Understanding np.searchsorted()
searchsorted() assumes its first argument is already sorted, and uses an efficient binary search, O(log n), rather than a linear scan, to find the insertion point for each value in values — it does not check or enforce that the array is actually sorted, so passing an unsorted array silently produces meaningless results. The side parameter controls tie-breaking when a value already exists in the array: 'left', the default, inserts before any existing equal elements, while 'right' inserts after them.
searchsorted() assumes the input array is already sorted and does not verify this — passing an unsorted array doesn't raise an error, it just silently returns an incorrect, meaningless insertion index.
import numpy as np
sorted_arr = np.array([1, 3, 5, 7, 9])
print(np.searchsorted(sorted_arr, 6))2Practical Example
Here is a real-world application of np.searchsorted() showing how it is used in production NumPy code.
import numpy as np
sorted_arr = np.array([1, 3, 5, 7, 9])
print(np.searchsorted(sorted_arr, [2, 5, 8]))3Best Practices
Follow these guidelines when working with np.searchsorted():
1. Only use searchsorted() on data you know is already sorted — sort it explicitly first if you're not certain
2. Use searchsorted() instead of a linear scan when repeatedly finding insertion points in a large sorted array, for its much better O(log n) performance
3. Choose side='left' or side='right' deliberately based on whether you want new values placed before or after existing equal ones
Tip: searchsorted() assumes the input array is already sorted and does not verify this — passing an unsorted array doesn't raise an error, it just silently returns an incorrect, meaningless insertion index.
import numpy as np
sorted_arr = np.array([1, 3, 5, 7, 9])
print(np.searchsorted(sorted_arr, 6))