Yolanda Hui
Yolanda Hui

Reputation: 97

TypeError: unhashable type: 'set'

I have the following code that gives me the union of set A and B, but it is giving me the error:

TypeError: unhashable type: 'set'

Code:

A = {1, {2}, 3}
B = {{1, {2}}, 3, 4}
A | B

What went wrong?

Upvotes: 0

Views: 14338

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

As @WilliemVanOnsem pointed out: sets are mutable and not hashable and can not be included in other sets.

If you need hashable sets you can use frozensets - wich are frozen (immutable) and hence hashable:

A = {1, frozenset({2}), 3}
B = {frozenset({1, frozenset({2})}), 3, 4}
print(A | B)

Output:

set([1, 3, 4, frozenset([2]), frozenset([1, frozenset([2])])])

Upvotes: 4

Related Questions