Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements.
Examples:
Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)]
Output : [(4, 5, 9)]
Explanation : Extracted tuples with all positive elements.Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)]
Output : []
Explanation : No tuple with all positive elements.
Method #1 : Using list comprehension + all()
In this, all() is used to check for all the tuples, list comprehension helps in the iteration of tuples.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using list comprehension + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = [sub for sub in test_list if all(ele >= 0 for ele in sub)] # printing resultprint("Positive elements Tuples : " + str(res)) |
The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]
Method #2 : Using filter() + lambda + all()
In this, the task of filteration is performed using filter() and lambda function.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using filter() + lambda + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list)) # printing resultprint("Positive elements Tuples : " + str(res)) |
The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]



