Use int(np.flatnonzero(arr == target)[0]) (or np.argmax(arr == target) after checking (arr == target).any()) to get the index of the first matching element in a 1D NumPy array without scanning or converting the entire array into a Python list, or tuple(int(i[0]) for i in np.nonzero(arr == target)) for multi-dimensional coordinates.
Basic Example
import numpy as np
arr = np.array([10, 42, 7, 42, 99])
target = 42
# 1. Recommended (1D array — safe & explicit):
matches = np.flatnonzero(arr == target)
first_idx = int(matches[0]) if matches.size > 0 else -1
print(first_idx)
# Output: 1
# 2. Fast short-circuiting check with `np.argmax` (stops at first True!):
mask = arr == target
first_idx_fast = int(np.argmax(mask)) if mask.any() else -1
print(first_idx_fast)
# Output: 1
# 3. Multi-dimensional array (returns first `(row, col, ...)` coordinate tuple):
grid = np.array([
[0, 5, 0],
[9, 5, 2],
])
coords = np.nonzero(grid == 5)
first_coord = tuple(int(c[0]) for c in coords) if coords[0].size > 0 else None
print(first_coord)
# Output: (0, 1)
Key Details & Edge Cases
- Why
np.argmax(arr == target)short-circuits at the very first match:np.argmax()on a boolean array stops scanning immediately upon hitting the firstTrue(1), making it faster thannp.where()/np.flatnonzero()on huge arrays when the match appears near the beginning.- Critical trap: If
targetis not inarr(soarr == targetis allFalse),np.argmax(mask)silently returns0—the exact same return value as whentargetis actually at index0! Always guard withif mask.any():(orif arr[0] == target:).
- Avoid
list(arr).index(target)orarr.tolist().index(target)on large arrays:- Calling
.tolist()allocates a full copy of the entire NumPy array as boxed Python objects in RAM before searching. Usenp.flatnonzero()ornp.argmax()directly on the NumPy boolean mask.
- Calling
- Finding the first occurrence of
NaNor floating-point values within tolerance:- Because
np.nan == np.nanis alwaysFalse,np.flatnonzero(arr == np.nan)always returns an empty array. Usenp.flatnonzero(np.isnan(arr))[0]forNaN, andnp.flatnonzero(np.isclose(arr, target))[0]for floating-point values subject to rounding error.
- Because
- Binary search in $O(\log n)$ when the 1D array is already sorted (
np.searchsorted):- If
arris sorted in ascending order,idx = int(np.searchsorted(arr, target, side="left"))locates the leftmost index in $O(\log n)$ time without scanning the array—verifyidx < arr.size and arr[idx] == targetto confirm the value actually exists rather than just returning an insertion point.
- If
Comparison of First-Index Lookup Methods in NumPy
| Method | Works on Multi-D Arrays? | Safe When Value Is Missing? | Time Complexity & Short-Circuiting | Best Used When |
|---|---|---|---|---|
np.flatnonzero(arr == target)[0] (Recommended) |
Yes (returns flattened index; use np.nonzero() for N-D tuple) |
Yes (raises IndexError if .size == 0, easy to guard) |
$O(n)$ C scan (collects all match indices) | General-purpose 1D or N-D lookup where clarity and safety matter most. |
np.argmax(arr == target) (with mask.any() guard) |
Yes (returns flattened index) | No without guard (returns 0 when missing!) |
$O(n)$ C scan, short-circuits at 1st match | Very large arrays where the target usually appears early and speed is critical. |
np.searchsorted(arr, target, side="left") |
No (1D sorted arrays only) | No without arr[idx] == target check |
$O(\log n)$ binary search | Already-sorted 1D arrays requiring repeated sub-millisecond lookups. |
next((i for i, v in enumerate(arr) if v == target), -1) |
No (1D only) | Yes (returns -1 sentinel) |
$O(n)$ slow Python loop (short-circuits) | Tiny 1D arrays (< 100 elements) where a match is expected in the first few items. |
You must log in or register to comment.
