0

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
1
  • 1
    A little bit of code to back up an assertion like "But tuples are immutable but not hashable" goes a long way. Commented Mar 12, 2014 at 6:17

3 Answers 3

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
1

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
1

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
2
  • An object doesn't have to be immutable to be hashable. Commented Mar 12, 2014 at 6:35
  • @brunodesthuilliers: Yes, you are right. I have made the correction. Commented Mar 12, 2014 at 6:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.