I heard about the line "immutable objects are hashable", below like this,
Frozensets are immutable and always hashable.
But tuples
are immutable but not hashable? Why?
user2864740
62.4k15 gold badges158 silver badges233 bronze badges
asked Mar 12, 2014 at 5:43
-
1A little bit of code to back up an assertion like "But tuples are immutable but not hashable" goes a long way.user2864740– user28647402014年03月12日 06:17:44 +00:00Commented Mar 12, 2014 at 6:17
3 Answers 3
Tuples are very much hashable if the elements inside are hashable.
>>> hashable = (1,2,4)
>>> not_hashable = ([1,2],[3,4])
>>> hash_check = {}
>>> hash_check[hashable] = True
>>> hash_check
{(1, 2, 4): True}
>>> hash_check[not_hashable] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
answered Mar 12, 2014 at 6:14
Even though tuples are immutable themselves, they might contain mutable objects, for example, if we could do:
person = {'name': 'John', 'surname': 'Doe'}
key = (person, True)
cache = {}
cache[key] = datetime.now() # for example
person['surname'] = 'Smith'
cache[key] # What is the expected result?
answered Mar 12, 2014 at 5:52
Not all immutable objects are hashable. Furthermore, only tuples that contain mutable objects are not hashable.
>>> t = (1, 2)
>>> hash(t)
1299869600
>>> t = ([1], [2])
>>> hash(t)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
hash(t)
TypeError: unhashable type: 'list'
So, the problem is the list, not the tuple.
answered Mar 12, 2014 at 5:49
-
An object doesn't have to be immutable to be hashable.bruno desthuilliers– bruno desthuilliers2014年03月12日 06:35:58 +00:00Commented Mar 12, 2014 at 6:35
-
@brunodesthuilliers: Yes, you are right. I have made the correction.Jayanth Koushik– Jayanth Koushik2014年03月12日 06:51:14 +00:00Commented Mar 12, 2014 at 6:51
lang-py