How do you find the index of the first occurrence of a value in a NumPy array? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you find the index of the first occurrence of a value in a NumPy array?

message-square
0

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 first True (1), making it faster than np.where() / np.flatnonzero() on huge arrays when the match appears near the beginning.
    • Critical trap: If target is not in arr (so arr == target is all False), np.argmax(mask) silently returns 0—the exact same return value as when target is actually at index 0! Always guard with if mask.any(): (or if arr[0] == target:).
  • Avoid list(arr).index(target) or arr.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. Use np.flatnonzero() or np.argmax() directly on the NumPy boolean mask.
  • Finding the first occurrence of NaN or floating-point values within tolerance:
    • Because np.nan == np.nan is always False, np.flatnonzero(arr == np.nan) always returns an empty array. Use np.flatnonzero(np.isnan(arr))[0] for NaN, and np.flatnonzero(np.isclose(arr, target))[0] for floating-point values subject to rounding error.
  • Binary search in $O(\log n)$ when the 1D array is already sorted (np.searchsorted):
    • If arr is 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—verify idx < arr.size and arr[idx] == target to confirm the value actually exists rather than just returning an insertion point.

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.