Python Set issubset() method



The Python Set issubset() method is used to check whether all elements of one set i.e the subset are contained within another set i.e. the superset. It returns True if every element of the subset is in the super-set and False otherwise.

This method can be used with other iterables like lists, tuples or strings as well. it is useful for verifying if one collection is completely contained within another which is a common operation in various algorithms and data analysis tasks.

Syntax

Following is the syntax and parameters of Python Set issubset() method −

set.issubset(iterable)

Parameter

This method accepts a set or iterable to compare with.

Return value

This method returns boolean value which is True if the given set is a subset of the current one otherwise, False.

Example 1

Following is the basic example of python set issubset() method. Here we created two sets and checked whether set1 is subset of set2 −

# Define two sets
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Check if set1 is a subset of set2
print(set1.issubset(set2))  

Output

True

Example 2

This example shows the issubset() method which is used to check two sets where one set is not a subset of the other −

# Define two sets
set1 = {1, 2, 6}
set2 = {1, 2, 3, 4, 5}

# Check if set1 is a subset of set2
print(set1.issubset(set2)) 

Output

False

Example 3

Here in this example we check whether the first set is subset of frozenset using the issubset() method −

# Define a set and a frozenset
my_set = {1, 2}
my_frozenset = frozenset({1, 2, 3})

# Check if the set is a subset of the frozenset
print(my_set.issubset(my_frozenset)) 

Output

True

Example 4

In this example we are checking whether an empty set is a subset of any set including itself.

# Define an empty set and a non-empty set
empty_set = set()
non_empty_set = {1, 2, 3}

# Check if the empty set is a subset of the non-empty set
print(empty_set.issubset(non_empty_set))  

# Check if the empty set is a subset of itself
print(empty_set.issubset(empty_set))

Output

True
python_set_methods.htm
Advertisements