Python – Check if Tuple contains only K elements

Sometimes, while working with Python tuples, we can have a problem in which we need to test if any tuple contains elements from set K elements. This kind of problem is quite common and have application in many domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be done.

Input : test_tuple = (1, 2, 3, 2, 1, 2), K = [1, 2, 3, 4]
Output : True

Input : test_tuple = (1, 2, 3), K = [1, 2]
Output : False

Method #1 : Using all()
This is one of the ways in which this task can be performed. In this, we check for the presence of all the elements in tuple are just from certain set of numbers using inbuilt function all().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Check if Tuple contains only K elements
# Using all()
  
# initializing tuple
test_tuple = (3, 5, 6, 5, 3, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# initializing K elements
K = [3, 6, 5]
  
# Check if Tuple contains only K elements
# Using all()
res = all(ele in K for ele in test_tuple)
  
# printing result 
print("Does tuples contains just from K elements : " + str(res))

chevron_right


Output :



The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True

 

Method #2 : Using set()
This is yet another way to solve this problem. In this, we convert the tuples, to set and then test the less and equal to relation with the query K elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Check if Tuple contains only K elements
# Using set()
  
# initializing tuple
test_tuple = (3, 5, 6, 5, 3, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# initializing K elements
K = [3, 6, 5]
  
# Check if Tuple contains only K elements
# Using all()
res = set(test_tuple) <= set(K)
  
# printing result 
print("Does tuples contains just from K elements : " + str(res))

chevron_right


Output :

The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




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.