In Python, why is a tuple hashable but not a list?

后端 未结 6 1893
我寻月下人不归
我寻月下人不归 2020-12-14 02:10

Here below when I try to hash a list, it gives me an error but works with a tuple. Guess it has something to do with immutability. Can someone explain this in detail ?

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 03:07

    Because a list is mutable, while a tuple is not. When you store the hash of a value in, for example, a dict, if the object changes, the stored hash value won't find out, so it will remain the same. The next time you look up the object, the dictionary will try to look it up by the old hash value, which is not relevant anymore.

    To prevent that, python does not allow you to has mutable items.

提交回复
热议问题