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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Positive Tuples in List
# Using list comprehension + all()
  
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() to check each element
res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]
  
# printing result
print("Positive elements Tuples : " + str(res))

chevron_right


Output

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Positive Tuples in List
# Using filter() + lambda + all()
  
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() to check each element
res = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list))
  
# printing result
print("Positive elements Tuples : " + str(res))

chevron_right


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.