Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find first instance of non zero number in list

Tags:

python

list

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?

like image 880
user2333196 Avatar asked Oct 21 '13 18:10

user2333196


People also ask

How do I find the first non-zero value of a list in Python?

Use the nonzero() Function to Find the First Index of an Element in a NumPy Array. The nonzero() function returns the indices of all the non-zero elements in a numpy array. It returns tuples of multiple arrays for a multi-dimensional array.

How do you find non-zero elements in a list Python?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .

How do I find the first number in a list Python?

python1min read To access the first element (12) of a list, we can use the subscript syntax [ ] by passing an index 0 . In Python lists are zero-indexed, so the first element is available at index 0 . Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.


1 Answers

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 
like image 186
Ashwini Chaudhary Avatar answered Sep 21 '22 15:09

Ashwini Chaudhary