 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
 