How to Compare Sets in Python?

Estimated read time 2 min read

To compare sets in Python, you can use various set operations and operators. Here are some commonly used methods and operators for comparing sets:

  1. Equality (==): You can use the equality operator (==) to check if two sets are equal, i.e., if they have the same elements.
set1 = {1, 2, 3}
set2 = {3, 2, 1}

if set1 == set2:
    print("set1 and set2 are equal")
    print("set1 and set2 are not equal")
  1. Subset (<= or issubset()): You can use the subset operator (<=) or the issubset() method to check if one set is a subset of another, i.e., if all elements of one set are present in another set.
set1 = {1, 2, 3}
set2 = {1, 2}

if set2 <= set1:
    print("set2 is a subset of set1")
    print("set2 is not a subset of set1")
  1. Superset (>= or issuperset()): You can use the superset operator (>=) or the issuperset() method to check if one set is a superset of another, i.e., if all elements of another set are present in one set.
set1 = {1, 2, 3}
set2 = {1, 2}

if set1 >= set2:
    print("set1 is a superset of set2")
    print("set1 is not a superset of set2")
  1. Disjoint (isdisjoint()): You can use the isdisjoint() method to check if two sets have no common elements, i.e., if their intersection is an empty set.
set1 = {1, 2, 3}
set2 = {4, 5, 6}

if set1.isdisjoint(set2):
    print("set1 and set2 are disjoint")
    print("set1 and set2 have at least one common element")

These are just a few examples of how you can compare sets in Python. Depending on your specific requirements, you can utilize other set operations and methods such as union, intersection, difference, etc.

Note that sets in Python are unordered collections of unique elements. When comparing sets, the order of elements does not matter.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply