Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Search From the Right Side

By default, the leftmost index is returned, but you can specify side='right' to return the rightmost index instead.

Example

Determine the indices where the value 7 should be inserted, starting from the right:

import numpy as np

arr = np.array([6789])

x = np.searchsorted(arr, 7, side=‘right’)

print(x)

Example explained: The number 7 should be inserted at index 2 to maintain the sort order.

The method searches from the right and returns the first index where 7 is not less than the next value.

Multiple Values

To search for multiple values, use an array containing the specified values.

Example

Determine the indices where the values 2, 4, and 6 should be inserted:

import numpy as np

arr = np.array([1357])

x = np.searchsorted(arr, [246])

print(x)