# First occurrence of True number in Python

PythonServer Side ProgrammingProgramming

In this article we are required to find the first occurring non-zero number in a given list of numbers.

## With enumerate and next

We sue enumerate to get the list of all the elements and then apply the next function to get the first non zero element.

## Example

Live Demo

listA = [0,0,13,4,17]
# Given list
print("Given list:\n " ,listA)
# using enumerate
res = next((i for i, j in enumerate(listA) if j), None)
# printing result
print("The first non zero number is at: \n",res)

## Output

Running the above code gives us the following result −

Given list:
[0, 0, 13, 4, 17]
The first non zero number is at:
2

## With next and filter

The next and filter conditions are applied to the elements of the list along with lambda expression with a condition not equal to zero.

## Example

listA = [0,0,13,4,17]
# Given list
print("Given list:\n " ,listA)
# using next,filetr and lambda
res = listA.index(next(filter(lambda i: i != 0, listA)))
# printing result
print("The first non zero number is at: \n",res)

## Output

Running the above code gives us the following result −

Given list:
[0, 0, 13, 4, 17]
The first non zero number is at:
2
Published on 04-Jun-2020 12:05:31