Sobes.tech
Junior
206

How is set equality checked in Python?

Answer from AI

sobes.tech AI

Two sets are considered equal if they contain the same elements. The order of elements does not matter.

The comparison is performed using the == operator. It compares the hashes of the elements in each set.

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

print(set1 == set2) // True - sets are equal
print(set1 == set3) // False - sets are different

Only hashable elements (numbers, strings, tuples) can be compared. Unhashable types (lists, dictionaries) cannot be elements of a set.

set_with_tuple = {(1, 2), (3, 4)}
set_with_tuple2 = {(3, 4), (1, 2)}
print(set_with_tuple == set_with_tuple2) // True

# You cannot create a set with a list or dictionary
# invalid_set = {[1, 2]} # TypeError: unhashable type: 'list'