
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Python - First occurrence of one list in another
- Sort tuple based on occurrence of first element in Python
- Index of first occurrence in StringCollection in C#?
- Add the occurrence of each number as sublists in Python
- Replace first occurrence of a character in Java
- Removing first occurrence of object from Collection in C#
- Python Pandas - Indicate duplicate index values except for the first occurrence
- Removing first occurrence of specified value from LinkedList in C#
- Python Pandas - Return Index with duplicate values removed except the first occurrence
- Get the index of the first occurrence of a separator in Java
- Remove the first occurrence from the StringCollection in C#
- Highest occurrence in an array or first selected in JavaScript
- Get the substring after the first occurrence of a separator in Java
- Get the first occurrence of a substring within a string in Arduino
- Count tuples occurrence in list of tuples in Python

Advertisements