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?
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.
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)] .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With