How to check if a tuple is a subset of another in Python

In this Python tutorial, we will learn how to check if a tuple is subset of another tuple. Basically tuple is a collection of heterogenous data and are typically immutable sequences. We can store integers as well as strings as elements in a tuple. Also, simultaneously we can store both integers and string values in a tuple.

Check if a tuple is a subset of another tuple in Python

The required Python code for the complete operation is shown below:

tuple1 = (11, 12, 4, 9, 5)
tuple2 = (4, 9)
print("The Original Tuple 1 is:" + str(tuple1))
print("The Original Tuple 2 is:" + str(tuple2))
temp_pranjal = set(tuple2).issubset(tuple1)
print("Is Tuple 2 subset of Tuple 1?" + "\n" + str(temp_pranjal))
  • As is evident from the above code we have taken two tuples and initialized them with integer values.
  • Then we have printed the original tuples using print statements of Python.
  • To check if one tuple is subset of another we have used type conversion of converting a tuple into a set and simply used issubset() to check if the second tuple is subset of the first tuple. Typeconversion refers to changing an entity of one data type into another.
  • And lastly, we have printed whether tuple 2 is subset of tuple 1 is ‘true’ or ‘false’.

Output:

The Original Tuple 1 is:(11, 12, 4, 9, 5)
The Original Tuple 2 is:(4, 9)
Is Tuple 2 subset of Tuple 1?
True

You can also read: Find common elements from two tuples in Python

For any further queries or doubts you may comment in the below comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *