Python – Extract tuple supersets from List

Sometimes, while working with Python tuples, we can have a problem in which we need to extract all the tuples, which have all the elements in target tuple. This problem can have application in domains such as web development. Let’s discuss certain way in which this problem can be solved.

Input :
test_list = [(5, 6, 6), (4, 2, 7), (9, 6, 5, 6)]
test_tuple = (6, 6)
Output : [(5, 6, 6), (9, 6, 5, 6)]

Input :
test_list = [(5, 6, 6), (4, 2, 6), (9, 6, 5, 6)]
test_tuple = (6, )
Output : [(5, 6, 6), (4, 2, 6), (9, 6, 5, 6)]

Method : Using Counter() + list comprehension + all()
The combination of above functions can be used to solve this problem. In this, we perform the task of counting using Counter(). The all(), is used to check if all elements form the subset and list comprehension is used to bind all the logic in one block.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract tuple supersets from List
# Using all() + list comprehension + Counter
from collections import Counter
  
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (9, 6, 5, 6)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing tuple
test_tup = (6, 6, 5)
  
# Extract tuple supersets from List
# Using all() + list comprehension + Counter
res = [sub for sub in test_list if 
       all(Counter(sub)[x] >= Counter(test_tup)[x]
       for x in Counter(test_tup))]
  
# printing result 
print("The superset tuples : " + str(res)) 

chevron_right


Output :

The original list is : [(5, 6, 8), (4, 2, 7), (9, 6, 5, 6)]
The superset tuples : [(9, 6, 5, 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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.