Q:

Python program to check if a tuple is a subset of another tuple

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to perform multiplication operation... >>
<< Python program to check if the element is present ...