This is a little faster (and looks nicer)

np.argmax(aa>5)

Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop
Answer from askewchan on Stack Overflow
🌐
Delft Stack
delftstack.com › home › howto › numpy › index of element in array
How to Find the First Index of Element in NumPy Array | Delft Stack
March 11, 2025 - One of the simplest and most effective ... satisfy a given condition. To find the first occurrence, you can simply access the first element of the result....
🌐
Data Science Dojo
discuss.datasciencedojo.com › python
How can I find the index of the first occurrence of a value in a NumPy array? - Python - Data Science Dojo Discussions
May 8, 2023 - Here is an example of my array: import numpy as np arr = np.array([4, 2, 3, 1, 4]) I want to find the index of the first occurrence of the value 4, which should be 0. I tried using the numpy.where() function, but it returns a tuple of arrays ...
🌐
IncludeHelp
includehelp.com › python › how-to-find-the-first-occurrence-of-subarray-in-numpy-array.aspx
Python - How to find the first occurrence of subarray in NumPy array?
December 26, 2023 - To find the first occurrence of the subarray, there is a straightforward approach is to use the rolling window technique to search for windows of the appropriate size. This approach is simple, works correctly, and is much faster than any pure Python solution.
Top answer
1 of 15
45

Although it is way too late for you, but for future reference: Using numba (1) is the easiest way until numpy implements it. If you use anaconda python distribution it should already be installed. The code will be compiled so it will be fast.

@jit(nopython=True)
def find_first(item, vec):
    """return the index of the first occurence of item in vec"""
    for i in xrange(len(vec)):
        if item == vec[i]:
            return i
    return -1

and then:

>>> a = array([1,7,8,32])
>>> find_first(8,a)
2
2 of 15
32

I've made a benchmark for several methods:

  • argwhere
  • nonzero as in the question
  • .tostring() as in @Rob Reilink's answer
  • python loop
  • Fortran loop

The Python and Fortran code are available. I skipped the unpromising ones like converting to a list.

The results on log scale. X-axis is the position of the needle (it takes longer to find if it's further down the array); last value is a needle that's not in the array. Y-axis is the time to find it.

The array had 1 million elements and tests were run 100 times. Results still fluctuate a bit, but the qualitative trend is clear: Python and f2py quit at the first element so they scale differently. Python gets too slow if the needle is not in the first 1%, whereas f2py is fast (but you need to compile it).

To summarize, f2py is the fastest solution, especially if the needle appears fairly early.

It's not built in which is annoying, but it's really just 2 minutes of work. Add this to a file called search.f90:

subroutine find_first(needle, haystack, haystack_length, index)
    implicit none
    integer, intent(in) :: needle
    integer, intent(in) :: haystack_length
    integer, intent(in), dimension(haystack_length) :: haystack
!f2py intent(inplace) haystack
    integer, intent(out) :: index
    integer :: k
    index = -1
    do k = 1, haystack_length
        if (haystack(k)==needle) then
            index = k - 1
            exit
        endif
    enddo
end

If you're looking for something other than integer, just change the type. Then compile using:

f2py -c -m search search.f90

after which you can do (from Python):

import search
print(search.find_first.__doc__)
a = search.find_first(your_int_needle, your_int_array)
🌐
Devgex
devgex.com › en › article › 00001821
Comprehensive Guide to Finding First Occurrence Index in NumPy Arrays - DevGex
October 28, 2025 - Unlike Python native lists, NumPy ... is crucial for mastering array operations. In Python lists, we can use the list.index() method to quickly find the first occurrence of an element:...
🌐
IncludeHelp
includehelp.com › python › numpy-find-first-index-of-value-fast.aspx
Python - NumPy: Find first index of value fast
For this purpose, we will look for the non-zero value in the NumPy array using the Bool value, it is zero then it must be False and would not return any value and if it is non-zero, it must return some value whose index would be fetched with the help of argmax() function. ... # Import numpy import numpy as np # Creating an array arr = np.array([1,0,5,0,9,0,4,6,8]) # Display original array print("Original Array:\n",arr,"\n") # Finding index of a value ind = arr.view(bool).argmax() res = ind if arr[ind] else -1 # Display result print("Result:\n",res,"\n")
Find elsewhere
Top answer
1 of 3
4

Benchmarking results

Well so I have decided to compare the proposed solutions in a typical case scenario. The three approaches are:

@timeit
def gener_sol(a):
    # My OP proposal
    return next(idx for idx in zip((i for i, x in enumerate(a) if x), (a.size-i-1 for i, x in enumerate(a[::-1]) if x)))

@timeit
def nonzero_sol(a):
    # kalzso's proposal
    return np.nonzero(a)[0][[0, -1]]

@timeit
def argmax_sol(a):
    # jan992's proposal
    return np.argmax(a), a.size - np.argmax(a[::-1]) - 1

NOTE: @timeit is a custom wrapper I have to measure functions execution time. Beyond the question whether it is perfect or not, it is the same for all of them so it should be a fair comparison.

And here goes the piece of code to execute them in a loop:

for rep in range(10000):
    N = 2**20  # Array size
    depth = N // 10  # max depth from the edges for first and last True
    
    arr = np.random.randint(0, 2, N).astype(bool)

    # First and last True values are randomly located at both ends
    first = random.randint(0, depth)
    arr[:first] = False
    arr[first]  = True

    last = random.randint(0, depth)
    arr[-last:] = False
    arr[-last]  = True

    arg_res = argmax_sol(arr)
    non_res = nonzero_sol(arr)
    gen_res = gener_sol(arr)

    # Ensure they all return the same
    assert arg_res == tuple(non_res) == gen_res

And the results are the following:

N=2^20 (10000 runs)

argmax_sol....:   10000 runs,       6.38 s  (638.01 μs/run)
nonzero_sol...:   10000 runs,     13.124 s  (1.312 ms/run)
gener_sol.....:   10000 runs,     42.695 s  (4.27 ms/run)

N=2^25 (100 runs)

argmax_sol....:     100 runs,      1.891 s  (18.908 ms/run)
nonzero_sol...:     100 runs,      4.125 s  (41.25 ms/run)
gener_sol.....:     100 runs,     13.799 s  (137.99 ms/run)

So, in this scenario the argmax solution is the clear winner, and the generator the clear loser. However, I noted that the depth at which the first and last indices are located (up to N/10 in this case) can have a significant impact. A reasonable value in my case is depth=10000 (or even less). Therefore, if I repeat the experiment I obtain:

N=2^20 (10000 runs) depth = 10000

gener_sol.....:     100 runs,    39.967 ms  (399.671 μs/run)
argmax_sol....:     100 runs,    58.851 ms  (588.505 μs/run)
nonzero_sol...:     100 runs,   138.077 ms  (1.381 ms/run)

As you see, in this case the generator yields better results. And the improvement is even larger if depth can be bound to even a smaller number.

See for instance:

N=2^20 (10000 runs) depth=1000

gener_sol.....:   10000 runs,      0.947 s  (94.753 μs/run)
argmax_sol....:   10000 runs,      6.082 s  (608.196 μs/run)
nonzero_sol...:   10000 runs,     14.282 s  (1.428 ms/run)

N=2^25 (1000 runs) depth=1000

gener_sol.....:    1000 runs,      0.053 s  (53.08 μs/run)
argmax_sol....:    1000 runs,      18.84 s  (18.84 ms/run)
nonzero_sol...:    1000 runs,     44.058 s  (44.058 ms/run)

wow, that's a dramatic improvement! ~6 and ~350 times faster than numpy's argmax for N=2^20 and 2^25, respectively. So one should not underestimate the power of for loops/generators under appropriate circumstances.

Finally, and to leave a good word for kalszo's nonzero solution, I do have found that there is a case in which it outperforms the others, and that is when the array is False everywhere except in two locations (the ones to find).

Therefore, changing the line:

# arr = np.random.randint(0, 2, N).astype(bool)
arr = np.zeros(N).astype(bool)

N=2^20 depth=N//10, only two True values

nonzero_sol...:   10000 runs,      1.612 s  (161.186 μs/run)
argmax_sol....:   10000 runs,      6.482 s  (648.178 μs/run)
gener_sol.....:   10000 runs,     44.625 s  (4.463 ms/run)

and with shallower depths:

N=2^20 (10000 runs) depth=10000, only two True values

nonzero_sol...:   10000 runs,      1.571 s  (157.093 μs/run)
gener_sol.....:   10000 runs,      4.208 s  (420.791 μs/run)
argmax_sol....:   10000 runs,      6.235 s  (623.512 μs/run)

N=2^25 (1000 runs) depth=10000, only two True values

gener_sol.....:    1000 runs,      0.433 s  (433.125 μs/run)
nonzero_sol...:    1000 runs,      5.427 s  (5.427 ms/run)
argmax_sol....:    1000 runs,     19.128 s  (19.128 ms/run)

N=2^20 (10000 runs) depth=1000, only two True values

gener_sol.....:   10000 runs,      0.962 s  (96.286 μs/run)
nonzero_sol...:   10000 runs,      1.637 s  (163.687 μs/run)
argmax_sol....:   10000 runs,      6.522 s  (652.228 μs/run)

again, the small depth relative to the array size is a key factor in favor of the generator expression.

In conclusion, the right solution depends very much on the scenario. For my particular case in which:

  • Arrays are large (2^20-2^25)
  • The array has multiple True values at unknown locations
  • The first and last True values are relatively close to the edges

the generator expression has the best performance with up to one or two orders of magnitude.

2 of 3
2

Use numpy's nonzero function, which returns the indices of all non-zero elements in the input array:

a = np.array([False, False, False, True, ..., True, False, False])

# Find the indices of the non-zero elements
indices = np.nonzero(a)

# The first and last indices will be the first and last True values
first = indices[0][0]
last = indices[0][-1]
🌐
Python Pool
pythonpool.com › home › numpy › get the first index in numpy arrays
5 Awesome Ways to Get First Index of Numpy - Python Pool
August 19, 2022 - Primary references include the NumPy where documentation, flatnonzero documentation, argmax documentation, argwhere documentation, and unravel_index documentation. ... For a one-dimensional array, index 0 returns the first element.
🌐
Kite
kite.com › python › answers › how-to-find-the-first-occurrence-of-an-element-of-a-numpy-array-greater-than-a-specified-value-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
🌐
pythontutorials
pythontutorials.net › blog › is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array
Is There a NumPy Function to Return the First Index of an Element in an Array? — pythontutorials.net
2D/High-Dimensional Arrays: Stick with np.where() (it handles coordinates naturally). Python lists have a built-in list.index(x) method that returns the first index of x. However, this only works on lists, not NumPy arrays.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-find-the-index-of-value-in-numpy-array
How to find the Index of value in Numpy Array ? - GeeksforGeeks
July 23, 2025 - # import numpy package import numpy ... first occurrence of each value sorter = np.argsort(a) print("index of first occurrence of each value: ", sorter[np.searchsorted(a, values, sorter=sorter)])...
🌐
pythontutorials
pythontutorials.net › blog › numpy-find-first-index-of-value-fast
Numpy: Fastest Way to Find First Index of a Value Without Scanning Entire Array (C-Compiled Methods) — pythontutorials.net
In this blog, we’ll explore the fastest NumPy-based (and C-compiled) methods to find the first index of a value without scanning the entire array. We’ll compare their performance, discuss edge cases, and provide best practices to implement them effectively. Problem Statement: Why Scanning the Entire Array Is Slow ... A Python for loop scans every element until it finds the target.
🌐
Statology
statology.org › home › how to find index of value in numpy array (with examples)
How to Find Index of Value in NumPy Array (With Examples)
September 17, 2021 - import numpy as np #define array ... of first occurrence of each value of interest sorter = np.argsort(x) sorter[np.searchsorted(x, vals, sorter=sorter)] array([0, 1, 4]) ... The value 4 first occurs in index position 0. The ...
🌐
Nabble
numpy-discussion.10968.n7.nabble.com › Implementing-a-quot-find-first-quot-style-function-td33085.html
Numpy-discussion - Implementing a "find first" style function
March 5, 2013 - Numpy-discussion · Implementing a "find first" style function · Locked 6 messages · Phil Elson · Reply | Threaded · Open this post in threaded view · Benjamin Root-2