Why doesn't Python hash lists using ID?

后端 未结 3 423
滥情空心
滥情空心 2021-01-02 17:26

When using a dictionary in Python, the following is impossible:

d = {}
d[[1,2,3]] = 4

since \'list\' is an unhashable type. Ho

3条回答
  •  醉话见心
    2021-01-02 18:27

    It is a requirement that if a == b, then hash(a) == hash(b). Using the id can break this, because the ID will not change if you mutate the list. Then you might have two lists that have equal contents, but have different hashes.

    Another way to look at it is, yes, you could do it, but it would mean that you could not retrieve the dict value with another list with the same contents. You could only retrieve it by using the exact same list object as the key.

提交回复
热议问题