Understanding the behavior of Python's set

When you initialize a set, you provide a list of values that must each be hashable.

s = set()
s.add([10])

is the same as

s = set([[10]])

which throws the same error that you're seeing right now.


In [13]: (2).__hash__
Out[13]: <method-wrapper '__hash__' of int object at 0x9f61d84>

In [14]: ([2]).__hash__ # nothing.

The thing is that set needs its items to be hashable, i.e. implement the __hash__ magic method (this is used for ordering in the tree as far as I know). list does not implement that magic method, hence it cannot be added in a set.


In this line:

s.add([10])

You are trying to add a list to the set, rather than the elements of the list. If you want ot add the elements of the list, use the update method.

Tags:

Python

Set