How to Compare Two Sets in Python?

Estimated read time 2 min read

To compare two sets in Python, you can use various methods and operators available for set operations. Here are a few common approaches:

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

if set1 == set2:
    print("The sets are equal")
else:
    print("The sets are not equal")

In this example, set1 and set2 contain the same elements, but their order is different. The equality comparison using == returns True, indicating that the sets are equal.

  1. Subset and Superset Comparison: You can use the issubset() and issuperset() methods to check if one set is a subset or superset of another.
set1 = {1, 2, 3}
set2 = {1, 2}

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

if set1.issuperset(set2):
    print("set1 is a superset of set2")
else:
    print("set1 is not a superset of set2")

In this example, set2 is a subset of set1, as it contains a subset of elements present in set1. The issubset() method returns True in this case. Similarly, set1 is a superset of set2, as it contains all the elements present in set2. The issuperset() method returns True in this case.

  1. Set Operations: You can use various set operations such as union (|), intersection (&), and difference (-) to compare and perform set operations between two sets.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Union of the two sets
union_set = set1 | set2
print("Union:", union_set)

# Intersection of the two sets
intersection_set = set1 & set2
print("Intersection:", intersection_set)

# Difference between the two sets
difference_set = set1 - set2
print("Difference:", difference_set)

In this example, the union of set1 and set2 contains all the unique elements from both sets. The intersection contains the common elements between the two sets. The difference contains the elements that are in set1 but not in set2. You can modify these operations based on your specific requirements.

These are some common methods and operations for comparing sets in Python. Choose the one that best fits your needs based on the specific comparison you want to perform.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply