Mars Lee
Mars Lee

Reputation: 1945

Why can't I make a difference set by Python?

So I make couple of experience:

>>>{2,3} - {2}
{3}

This one works perfectly.

However, this one seems not work:

>>> {{2,3},{4,3}} - {{4,3}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

I deem that it should work,

because I use one set contain two element, {2,3} and {4,3} to minus one element {4,3}.

Nonetheless, it just can't work. Why?

Upvotes: 2

Views: 115

Answers (1)

falsetru
falsetru

Reputation: 369494

sets are not hashable; cannot be member of set. Use frozenset instead:

>>> {frozenset({2,3}), frozenset({4,3})} - {frozenset({4,3})}
set([frozenset([2, 3])])

According to set / frozenset documentation:

The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.


hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

Upvotes: 6

Related Questions