Python Forum
hashable confusion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: hashable confusion (/thread-29056.html)



hashable confusion - spalisetty06 - Aug-16-2020

Hello,
I have read that all data types which are immutable are hashable. But, [b]set[b] is mutable. How is that it is stored based on hash value?


RE: hashable confusion - buran - Aug-16-2020

As stated in docs,
Quote:A set object is an unordered collection of distinct hashable objects.
...
There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

>>> spam = {1, 2}
>>> type(spam)
<class 'set'>
>>> eggs = {spam}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> spam = frozenset(spam)
>>> type(spam)
<class 'frozenset'>
>>> eggs = {spam}
>>> type(eggs)
<class 'set'>



RE: hashable confusion - deanhystad - Aug-16-2020

In other words, set is not hashable but frozen set is.
a = {1, 2, 3}
b = frozenset(a)
print(a.__hash__, b.__hash__)
Output:
None <method-wrapper '__hash__' of frozenset object at 0x0000027837D3F120>
There is no __hash__ method defined for set, but there is for frozenset.


RE: hashable confusion - spalisetty06 - Aug-16-2020

okay, so, it's hashable only for forzen set and not for set. Thank You.