NumPy Searching
flatnonzero finds matching positions in a one-dimensional condition, while searchsorted finds insertion points in a sorted sequence. These answer different questions.
How it works
searchsorted assumes its input is ordered appropriately; it does not sort the data or prove that a matching value exists. left and right control which edge of an equal-value run is returned. Use these boundaries for a range search and check equality when you actually need an existing item. A position is not the same as the value stored at that position.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python searching.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
values = np.array([6, 12, 12, 24])
print(np.flatnonzero(values == 12).tolist())
print(int(np.searchsorted(values, 12, side="left")))
print(int(np.searchsorted(values, 12, side="right")))
print(int(np.searchsorted(values, 15)))
Expected result
[1, 2] 1 3 3
The value twelve occupies two positions, while fifteen would be inserted before twenty-four. Its insertion position does not mean fifteen already exists. This distinction prevents an apparent lookup from returning the wrong record.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.