how to check if a set is a superset of another set in python

To check whether a set is a superset of another set in Python, you can use the issuperset() method. This method returns True if all elements of the other set are present in the calling set. Here's an example:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}

print(set1.issuperset(set2))  # Output: True
83 chars
5 lines

In this example, set1 is a superset of set2 since set1 contains all elements of set2. Note that if set2 contains elements not present in set1, then set1 is not a superset of set2.

You can also use the >= operator to check if a set is a superset of another set. It returns the same result as the issuperset() method. Here's an example:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}

print(set1 >= set2)  # Output: True
74 chars
5 lines

In addition, you can use the issubset() method to check if a set is a subset of another set. This method returns True if all elements of the calling set are present in the other set. Here's an example:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}

print(set2.issubset(set1))  # Output: True
81 chars
5 lines

Finally, you can use the < operator to check if a set is a proper subset of another set. This operator returns True if all elements of the calling set are present in the other set and the other set has additional elements. Here's an example:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}

print(set2 < set1)  # Output: True
73 chars
5 lines

gistlibby LogSnag