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 e
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]
.
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.
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
How'bout this :
[i for i, x in enumerate(myList) if x][0]
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
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