
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
First Occurrence of True Number in Python
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
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
Advertisements