Home »
Python »
Python programs
Python program to check if a tuple is a subset of another tuple
In this program, we are given two tuples with integer elements. We need to create a Python program to check if one tuple is a subset of another tuple.
Submitted by Shivang Yadav, on December 19, 2021
Python has a lot of applications where we need to check for the similarities in two collections to avoid extracting evaluation of the value and make programs more effective. Here, we will see a Python program to check if a tuple is a subset of another tuple.
Before going further with the problem, let's recap some basic topics that will help in understanding the solution.
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
Check if a tuple is a subset of another tuple
In this article, we are given two tuples. And we need to create a Python program to check if a tuple is a subset of another tuple.
Input:
Tup1 = (4, 1, 6)
Tup2 = (2, 4, 8, 1, 6, 5)
Output:
true
This can be done by checking the presence of elements tup1 in tup2. And python provides multiple methods to check for the sam.
Method 1:
One method to solve the problem is by using the issubset() method which checks if one tuple is a subset of another subset.
# Python program to check if a tuple
# is a subset of another tuple
# Initializing and printing tuple
tup1 = (4, 1, 6)
tup2 = (2, 4, 8, 1, 6, 5)
print("The elements of tuple 1 : " + str(tup1))
print("The elements of tuple 2 : " + str(tup2))
# Checking for subsets
isSubset = set(tup1).issubset(tup2)
if isSubset :
print("tup1 is a subset of tup2")
else :
print("tup1 is not a subset of tup2")
Output:
The elements of tuple 1 : (4, 1, 6)
The elements of tuple 2 : (2, 4, 8, 1, 6, 5)
tup1 is a subset of tup2
Method 2:
Another method to solve the problem is by using all method to check if all elements of the 1st tuple are present in the 2nd tuple.
# Python program to check if a tuple
# is a subset of another tuple
# Initializing and printing tuple
tup1 = (4, 1, 6)
tup2 = (2, 4, 8, 1, 6, 5)
print("The elements of tuple 1 : " + str(tup1))
print("The elements of tuple 2 : " + str(tup2))
# Checking for subsets
isSubset = all(ele in tup2 for ele in tup1)
if isSubset :
print("tup1 is a subset of tup2")
else :
print("tup1 is not a subset of tup2")
Output:
The elements of tuple 1 : (4, 1, 6)
The elements of tuple 2 : (2, 4, 8, 1, 6, 5)
tup1 is a subset of tup2
Python Tuple Programs »