Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
First occurrence of True number in Python
In this article, we will find the first occurrence of a non-zero (True) number in a given list. In Python, zero evaluates to False while non-zero numbers evaluate to True, making this a common programming task.
Using enumerate() with next()
The enumerate() function provides both index and value, while next() returns the first matching element ?
Example
numbers = [0, 0, 13, 4, 17]
# Given list
print("Given list:", numbers)
# Using enumerate to get index of first non-zero number
result = next((i for i, j in enumerate(numbers) if j), None)
# Printing result
print("The first non-zero number is at index:", result)
Given list: [0, 0, 13, 4, 17] The first non-zero number is at index: 2
Using next() with filter()
The filter() function with a lambda expression filters out zero values, then index() finds the position ?
Example
numbers = [0, 0, 13, 4, 17]
# Given list
print("Given list:", numbers)
# Using next, filter and lambda
first_nonzero = next(filter(lambda i: i != 0, numbers))
result = numbers.index(first_nonzero)
# Printing result
print("The first non-zero number is at index:", result)
print("The first non-zero number is:", first_nonzero)
Given list: [0, 0, 13, 4, 17] The first non-zero number is at index: 2 The first non-zero number is: 13
Using a Simple Loop
A straightforward approach using a for loop to find the first non-zero number ?
Example
numbers = [0, 0, 13, 4, 17]
# Given list
print("Given list:", numbers)
# Using simple loop
for i, num in enumerate(numbers):
if num != 0:
print("The first non-zero number is at index:", i)
print("The first non-zero number is:", num)
break
else:
print("No non-zero number found")
Given list: [0, 0, 13, 4, 17] The first non-zero number is at index: 2 The first non-zero number is: 13
Comparison
| Method | Readability | Performance | Returns |
|---|---|---|---|
enumerate() + next() |
Good | Fast | Index only |
filter() + next() |
Medium | Medium | Value and index |
| Simple loop | Excellent | Fast | Both value and index |
Conclusion
Use enumerate() with next() for a concise solution when you only need the index. For better readability and when you need both value and index, a simple loop is often the best choice.
Advertisements
