Find the first instance of a nonzero number in 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
Find first instance of non zero number in list after an index value
You can try this one !
myarray=[45,45,1,0,0,0,8,6,7]
def firstNon0(_list,startindex):
for index in range(startindex,len(_list)):
if _list[index]!=0:return index
return None
print myarray[firstNon0(myarray,3)]
>>8
how to find first index of any number except 0 in python list?
You could use enumerate
to iterate over the indices and values. Then use next
to stop upon finding the first non-zero value. If StopIteration
was thrown, the list contained no non-zero values, so do whatever error handling you'd like there.
def first_non_zero(values):
try:
return next(idx for idx, value in enumerate(values) if value != 0)
except StopIteration:
return None
Examples
>>> list1 = [0,0,0,0,4,3,2,0,3]
>>> first_non_zero(list1)
4
>>> first_non_zero([0,0,0])
>>> # None
Find first instance of non zero number in list after an index value
You can try this one !
myarray=[45,45,1,0,0,0,8,6,7]
def firstNon0(_list,startindex):
for index in range(startindex,len(_list)):
if _list[index]!=0:return index
return None
print myarray[firstNon0(myarray,3)]
>>8
Find first non zero numbers in an array (zeroes can be anywhere)
You can do this
x = [10,0,30,40]
for var in x:
if var != 0:
y = var
break
how do I capture the first non-zero integer from the back of an integer?
To achieve this you should first convert the integer 'n' to a string and iterate through it in the reverse order.
Below is the code for demonstrating this.
def last_digit(n):
n=str(n)
rev=n[::-1] # Reversing the string 'n'
for i in rev:
if i!='0' :
print(i)
break
The first non-zero element in each row
If I understood correctly, the break should be inside the if statement
if a[i,j]!=0:
print(i+1,'-th row,',j+1,'-th column','\nthe 1st non-zero element:',a[i,j],'\n---')
break
Related Topics
Best Way to Structure a Tkinter Application
How to Rotate an Image Around Its Center Using Pygame
Redirect Stdout to a File in Python
Configure Flask Dev Server to Be Visible Across the Network
How to Do Relative Imports in Python
Why Does "Return List.Sort()" Return None, Not the List
How to Check If a String Is a Number (Float)
How to Concatenate Str and Int Objects
How to Break Out of Multiple Loops
How to Put the Legend Outside the Plot
How to Concatenate Items in a List to a Single String
Finding the Index of an Item in a List
Python-Dev Installation Error: Importerror: No Module Named Apt_Pkg
Simulating Key Press Event Using Python For Linux
Using Pip3: Module "Importlib._Bootstrap" Has No Attribute "Sourcefileloader"