HOWTO · NumPy
How to Find the First Index of Element in NumPy Array
Learn how to find the first matching index in a NumPy array with np.where(), np.nonzero(), np.argmax(), list.index(), and a loop.
On this page
To find the first index of a value in a one-dimensional NumPy array, use np.where(array == value)[0][0] when a match is guaranteed. The expression returns the first matching position; use a presence check when the value may be absent. NumPy indices start at zero.
Find the First Matching Index with np.where()
np.where(condition) returns a tuple containing an array of indices for each dimension. For a one-dimensional array, the first tuple item is the list of matching positions. Select its first item to get the first match.
Run this example:
import numpy as np
values = np.array([10, 20, 30, 40, 50, 20])
target = 20
matches = np.where(values == target)[0]
print(int(matches[0]))
1
Here, matches contains both positions where 20 occurs, and matches[0] selects the first one. If no value matches, matches has no elements, so indexing it raises IndexError. Check matches.size before selecting an index when a match is not guaranteed. The three-argument form, np.where(condition, x, y), instead chooses values from x or y; it is not the index-returning form shown here.
Use np.nonzero() to Find Matching Indices
For a Boolean condition, np.nonzero() returns the indices of its true entries. Like the one-argument form of np.where(), it returns a tuple of index arrays, one per array dimension. For a one-dimensional array, take the first array in that tuple.
import numpy as np
values = np.array([4, 7, 4, 9])
positions = np.nonzero(values == 4)[0]
print(positions.tolist())
The result contains every matching position, in array order. Use positions[0] for the first match only after checking that the array is nonempty. For a multidimensional array, each tuple item contains coordinates along one dimension; pair corresponding entries to address each match.
Use np.argmax() for a Boolean Match
np.argmax() returns the position of the largest value. Applied to a Boolean mask, it returns the position of the first True, because True is greater than False. An all-false mask also produces 0, so check that a match exists before using the result.
import numpy as np
values = np.array([5, 8, 3, 8])
mask = values == 8
first = int(np.argmax(mask)) if np.any(mask) else None
print(first)
This pattern yields None when the target is absent and the first matching position otherwise. For all matching positions, use np.where() or np.nonzero() instead.
Use list.index() After Converting the Array
Converting a one-dimensional array to a Python list lets you use the list method list.index(). It returns the first occurrence. The conversion creates a Python list, so this approach adds time and memory overhead and is usually most convenient for small arrays or code already using lists.
import numpy as np
values = np.array([10, 20, 30, 20])
items = values.tolist()
target = 20
index = items.index(target) if target in items else None
print(index)
The membership check makes the missing-value result explicit as None; calling items.index(target) directly when the value is absent raises ValueError. The check and lookup each scan the list, so for a single lookup you can instead catch ValueError around list.index().
Use a Loop for Custom Logic
A loop is useful when each element needs a custom test that is awkward to express as a vectorized NumPy condition. Initialize the result to a not-found value, then stop as soon as the first match appears.
import numpy as np
values = np.array([12, 15, 18, 21])
index = None
for position, value in enumerate(values):
if value % 2 == 0 and value > 12:
index = position
break
print(index)
The loop examines elements one at a time and exits at the first value meeting both conditions. For a simple equality check, a NumPy mask is usually more concise; use the loop when the matching rule needs custom branching or state.
Handle Missing Matches, Repeated Values, and Array Dimensions
Choose the result shape that matches your task:
- For the first match in a one-dimensional array, obtain the positions with
np.where()ornp.nonzero(), check that at least one exists, and select the first position. - For every match, keep the full index array. Repeated values produce multiple positions; do not select
[0]if you need them all. - For a two-dimensional array,
np.where(matrix == target)returns(row_indices, column_indices). Corresponding entries form coordinate pairs. For example,(rows[0], columns[0])is the row and column of the first match, not a single flat index. - If you specifically need a flat position in a multidimensional array, flatten the array first and search the flattened values. Convert that flat position back to coordinates with
np.unravel_index()when needed. np.argmax()returns zero for a nonempty all-false mask, but that position does not indicate a match. If the mask is empty,np.argmax()raisesValueErrorinstead. The guarded expression above checksnp.any(mask)first, so it returnsNonefor either a mask with no true entries or an empty mask.
For typical numeric array lookup, np.where() is a direct choice when you need the first match or all matches. Use np.nonzero() for the same true-condition positions, np.argmax() for a checked Boolean mask, list.index() when a Python list is already useful, and a loop for custom matching rules.