49

I have a list like this:

myList = [0.0, 0.0, 0.0, 2.0, 2.0]

I would like to find the location of the first number in the list that is not equal to zero.

myList.index(2.0)

It works in this example, but sometimes the first nonzero number will be 1 or 3.

Is there a fast way of doing this?

3

9 Answers 9

64

Use next with enumerate:

>>> myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
>>> next((i for i, x in enumerate(myList) if x), None) # x!= 0 for strict match
3
2
  • What would be the equivalent for numpy arrays ? Commented Dec 15, 2020 at 18:58
  • It begs questions about comparison of floating numbers. E.g., what would happen if 42.8/21.4 was used instead of 2.0? Can you address comparison of floating numbers in your answer (even if it is somehow automatically handled (rounding, etc.))? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today. And without reference to this comment.) Commented Feb 4, 2022 at 12:58
21

Use filter

Python 2:

myList = [0.0, 0.0, 0.0, 2.0, 2.0]
myList2 = [0.0, 0.0]

myList.index(filter(lambda x: x!=0, myList)[0])       # 3
myList2.index(filter(lambda x: x!=0, myList2)[0])     # IndexError

Python 3: (Thanks for Matthias's comment):

myList.index(next(filter(lambda x: x!=0, myList)))    # 3
myList2.index(next(filter(lambda x: x!=0, myList2)))  # StopIteration
# from Ashwini Chaudhary's answer
next((i for i, x in enumerate(myList) if x), None)    # 3
next((i for i, x in enumerate(myList2) if x), None)   # None

You have to handle special case.

3
  • 2
    Great alternative too, main difference from next is that next provides a default value whereas this would raise an exception.
    – Wtower
    Commented Mar 30, 2015 at 12:18
  • 3
    for python 3 you can use myList.index(next(filter(lambda x: x!=0, myList)))
    – Matthias
    Commented Sep 29, 2016 at 13:48
  • 1
    I like this answer best, but with the Matthias mod to use "next". Note that in either case, depending on the situation you should consider a test of any(myList) first, to make sure there is at least one nonzero value. It may help with program flow and avoiding exceptions.
    – Starman
    Commented Apr 9, 2019 at 21:01
12

You can use numpy.nonzero:

myList = [0.0, 0.0, 0.0, 2.0, 2.0]
I = np.nonzero(myList)
# The first index is necessary because the vector is within a tuple
first_non_zero_index = I[0][0]
# 3
6

Here's a one liner to do it:

val = next((index for index,value in enumerate(myList) if value != 0), None)

Basically, it uses next() to find the first value, or return None if there isn't one. enumerate() is used to make an iterator that iterates over index,value tuples so that we know the index that we're at.

5

Use this:

[i for i, x in enumerate(myList) if x][0]
3

Using next with enumerate is excellent when the array is large. For smaller arrays, I would use argmax from NumPy so that you won't need a loop:

import numpy as np

myList = [0.0, 0.0, 0.0, 2.0, 2.0]
myArray = np.array(myList)
np.argmax(myArray > 0)
3
2
  • 3
    This will not find the first nonzero element, e.g. for [0, 0, 1, 2].
    – cheersmate
    Commented Oct 8, 2018 at 13:39
  • Yes it will, but it's not very intuitive. All elements in myArray > 0 are either False or True, so the maximum of that array is True. According to the documentation for numpy.argmax, "In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned." So with your example, if myArray is [0, 0, 1, 2], then myArray > 0 is [False, False, True, True] and the argmax of that is 2. Commented Feb 13, 2023 at 14:23
1

What about using enumerate? Check the enumerate documentation.

def first_non_zero(mylist):
  for index, number in enumerate(mylist):
    if number != 0: # or 'if number:'
      return index
0
1

Do the following:

print (np.nonzero(np.array(myList))[0][0])

This is more convenient, because along with finding nonzero values, this can also help to apply logic function directly. For example:

print (np.nonzero(np.array(myList)>1))
1
  • Perhaps elaborate a little bit in your answer how floating point comparisons are handled? Presumably it is not exact comparison. (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.) Commented Feb 4, 2022 at 13:15
0

Simply use a list comprehension:

myDict = {x: index for index, x in enumerate(myList) if x}

The indices of the nonzero elements are myDict[element].

1
  • 1
    This doesn't give the index, it just filters out the non-zero elements from the list. Commented Oct 21, 2013 at 18:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.