Python find first instance of non zero number in list

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

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.


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.

Tags:

Python

List