[Solved] how to find first index of any number except 0 in python list? [closed]


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

2

solved how to find first index of any number except 0 in python list? [closed]