Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
hashable confusion
#1
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?
Reply
#2
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'>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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.
Reply
#4
okay, so, it's hashable only for forzen set and not for set. Thank You.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  confusion with hashable spalisetty06 5 2,637 Aug-21-2020, 07:44 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020