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
Python program to find Tuples with positive elements in List of tuples
When it is required to find tuples that have positive elements from a list of tuples, list comprehension along with the all() function can be used. This approach checks if all elements in each tuple are non-negative.
Syntax
result = [tuple for tuple in list_of_tuples if all(element >= 0 for element in tuple)]
Example
The following example demonstrates how to filter tuples containing only positive elements ?
my_list = [(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)]
print("The list is:")
print(my_list)
my_result = [sub for sub in my_list if all(elem >= 0 for elem in sub)]
print("The tuples with positive elements are:")
print(my_result)
Output
The list is: [(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)] The tuples with positive elements are: [(56, 43), (24, 56)]
How It Works
The
all()function returnsTrueif all elements in an iterable areTrue(or non-zero)List comprehension iterates through each tuple in the original list
For each tuple,
all(elem >= 0 for elem in sub)checks if every element is non-negativeOnly tuples where all elements pass the condition are included in the result
Alternative Method Using filter()
You can also use the filter() function with a lambda expression ?
my_list = [(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)]
print("The list is:")
print(my_list)
my_result = list(filter(lambda x: all(elem >= 0 for elem in x), my_list))
print("The tuples with positive elements are:")
print(my_result)
Output
The list is: [(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)] The tuples with positive elements are: [(56, 43), (24, 56)]
Conclusion
Use list comprehension with all() function to efficiently filter tuples containing only positive elements. The filter() method provides an alternative functional programming approach for the same task.
