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

后端 未结 6 1891
我寻月下人不归
我寻月下人不归 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 02:45

    I would like to add the following aspect as it's not covered by other answers already.

    There's nothing wrong about making mutable objects hashable, it's just not unambiguous and this is why it needs to be defined and implemented consistently by the programmer himself (not by the programming language).

    Note that you can implement the __hash__ method for any custom class which allows its instances to be stored in contexts where hashable types are required (such as dict keys or sets).

    Hash values are usually used to decide if two objects represent the same thing. So consider the following example. You have a list with two items: l = [1, 2]. Now you add an item to the list: l.append(3). And now you must answer the following question: Is it still the same thing? Both - yes and no - are valid answers. "Yes", it is still the same list and "no", it has not the same content anymore.

    So the answer to this question depends on you as the programmer and so it is up to you to manually implement hash methods for your mutable types.

提交回复
热议问题