When it is required to find tuples with positive elements in a list of tuples, list comprehension and ‘all’ operator is used.
Example
Below is a demonstration of the same −
my_tuple = [(14, 15, 19), (-32, 23, 32), (-31, 15, 63), (46, 68)] print("The list is :") print(my_tuple) my_result = [sub for sub in my_tuple if all(element >= 0 for element in sub)] print("The result is :") print(my_result)
Output
The list is : [(14, 15, 19), (-32, 23, 32), (-31, 15, 63), (46, 68)] The result is : [(14, 15, 19), (46, 68)]
Explanation
A list of tuple of integers is defined and is displayed on the console.
A list comprehension is used to iterate over the elements and check if element is greater than 0.
This is done using ‘all’ operator and is converted to a list.
This is assigned to a variable.
This is the output that is displayed on the console.