What makes lists unhashable?

后端 未结 1 865
后悔当初
后悔当初 2020-12-19 06:38

So lists are unhashable:

>>> { [1,2]:3 }
TypeError: unhashable type: \'list\'

The following page gives an explanation:

相关标签:
1条回答
  • 2020-12-19 07:11

    Dictionaries and sets use hashing algorithms to uniquely determine an item. And those algorithms make use of the items used as keys to come up the unique hash value. Since lists are mutable, the contents of a list can change. After allowing a list to be in a dictionary as a key, if the contents of the list changes, the hash value will also change. If the hash value changes after it gets stored at a particular slot in the dictionary, it will lead to an inconsistent dictionary. For example, initially the list would have gotten stored at location A, which was determined based on the hash value. If the hash value changes, and if we look for the list we might not find it at location A, or as per the new hash value, we might find some other object.

    Since, it is not possible to come up with a hash value, internally there is no hashing function defined for lists.

    PyObject_HashNotImplemented,                /* tp_hash */
    

    As the hashing function is not implemented, when you use it as a key in the dictionary, or forcefully try to get the hash value with hash function, it fails to hash it and so it fails with unhashable type

    TypeError: unhashable type: 'list'
    
    0 讨论(0)
提交回复
热议问题