Python Program to Check if Two Sets Are Equal
In Python, sets are an unordered collection of unique elements. That means each element occurs only once in the set. You can use sets for checking two sets are equal. Let’s create a program to check if two sets are equal.
Example Program
# Declare two sets
set1 = {1, 2, 3, 4, 5}
set2 = set()
# Add elements to set2
set2.add(5)
set2.add(4)
set2.add(3)
set2.add(2)
set2.add(1)
# Compare sets
if (set1 == set2):
print("Both sets are equal")
else:
print("Sets are not equal")
This program declares two sets set1
and set2
. set1
includes elements from 1 to 5, and set2
is empty. Then the program adds elements 1 to 5 to set2
. Finally, it compares the two sets by using the ==
operator. If the two sets are equal, the program prints "Both sets are equal", else "Sets are not equal."
Output:
Both sets are equal
Explanation
Python set can be compared using the ==
operator. The ==
operator will return True
if both sets have the same elements, regardless of the order of elements. If the sets are not equal, then the ==
operator will return False
.
Sorting Sets
Since sets are unordered by nature, some situations require you to sort sets. To sort a set in Python, you can use the sorted()
function.
set1 = {3, 2, 1, 4, 5}
sorted_set1 = sorted(set1)
set2 = {5, 3, 1, 2, 4}
sorted_set2 = sorted(set2)
# Compare sorted sets
if (sorted_set1 == sorted_set2):
print("Both sets are equal")
else:
print("Sets are not equal")
This program sorts two sets set1
and set2
using the sorted()
function. Then, it compares the two sets by using the ==
operator. If the two sets are equal, the program prints "Both sets are equal", else "Sets are not equal."
Output:
Both sets are equal
Conclusion
In this article, we have discussed how to check if two sets are equal in Python. We can use the ==
operator to compare two sets. If you want to compare sets irrespective of their order, then you can sort the sets using the sorted()
function.