List unhashable, but tuple hashable?

前端 未结 6 872
渐次进展
渐次进展 2020-12-08 10:15

In How to hash lists? I was told that I should convert to a tuple first, e.g. [1,2,3,4,5] to (1,2,3,4,5).

So the first cannot be hashed, bu

6条回答
  •  悲哀的现实
    2020-12-08 10:23

    Since a list is mutable, if you modify it you would modify its hash too, which ruins the point of having a hash (like in a set or a dict key).

    Edit: I'm surprised this answer regularly get new upvotes, it was really quickly written. I feel I need to make it better now.

    So the set and the dict native data structures are implemented with a hashmap. Data types in Python may have a magic method __hash__() that will be used in hashmap construction and lookups.

    Only immutable data types (int, string, tuple, ...) have this method, and the hash value is based on the data and not the identity of the object. You can check this by

    >>> a = (0,1)
    >>> b = (0,1)
    >>> a is b
    False # Different objects
    >>> hash(a) == hash(b)
    True # Same hash
    

    If we follow this logic, mutating the data would mutate the hash, but then what's the point of a changing hash ? It defeats the whole purpose of sets and dicts or other hashes usages.

    Fun fact : if you try the example with strings or ints -5 <= i <= 256, a is b returns True because of micro-optimizations (in CPython at least).

提交回复
热议问题