Python | Check if one tuple is subset of other

• Last Updated : 21 Nov, 2019

Sometimes, while working with Python, we can work with different data and we might need to solve problem of checking if one subset is part of other. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using issubset()
We can solve this problem using type conversion of tuple into a set and then check if one tuple is subset of other using issubset().

 # Python3 code to demonstrate working of# Check if one tuple is subset of other# using issubset()  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 10)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Check if one tuple is subset of other# using issubset()res = set(test_tup2).issubset(test_tup1)  # printing resultprint("Is 2nd tuple subset of 1st ? : " + str(res))
Output :
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 10)
Is 2nd tuple subset of 1st ? : True

Method #2 : Using all() + generator expression
The combination of above functionalities can also perform this task. In this, we check for each element of one tuple with another using expression and all().

 # Python3 code to demonstrate working of# Check if one tuple is subset of other# using all() + generator expression  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 10)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Check if one tuple is subset of other# using all() + generator expressionres = all(ele in test_tup1 for ele in test_tup2)  # printing resultprint("Is 2nd tuple subset of 1st ? : " + str(res))
Output :
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 10)
Is 2nd tuple subset of 1st ? : True

My Personal Notes arrow_drop_up