How to Compare Sets Using the issubset() Function in Python?

Estimated read time 2 min read

To compare sets using the issubset() function in Python, you can use it to check if one set is a subset of another set. The issubset() function returns True if all elements of one set are present in another set, and False otherwise. Here’s an example:

set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}

if set2.issubset(set1):
    print("set2 is a subset of set1")
else:
    print("set2 is not a subset of set1")

In this example, we have two sets, set1 and set2. We use the issubset() function on set2 and pass set1 as the argument. The function checks if all elements of set2 are present in set1. If set2 is indeed a subset of set1, the code will print “set2 is a subset of set1”. Otherwise, it will print “set2 is not a subset of set1”.

The output of the above code will be:

set2 is a subset of set1

You can also use the <= operator to achieve the same comparison. The <= operator is equivalent to the issubset() function. Here’s an example using the <= operator:

set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}

if set2 <= set1:
    print("set2 is a subset of set1")
else:
    print("set2 is not a subset of set1")

The output will be the same as the previous example.

By using the issubset() function or the <= operator, you can compare sets in Python to check if one set is a subset of another.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply