1

I understand why tuple is hashable but list is not. But if python makes user-defined objects hashable by default using their ID, why can't they do the same for list?

Jingxi Xu
  • 47
  • 3
  • 1
    A list is *known* to be unsafe for hashing. It’s up to you to ensure the safe usability of your custom classes. – deceze Apr 11 '22 at 19:25
  • 1
    I don't think this should be closed... They *could* make `list`s hashable. It's not a technical issue, it's a design decision. – jmd_dk Apr 11 '22 at 19:26
  • 1
    Oh, did I reopen this immediately? I meant to vote and say that this particular question seems to be about why user-defined objects/classes (which are mutable, just like lists) are hashable, but lists (which are mutable, just like most basic user-defined objects) are not. The dupe target doesn't seem to address this – ForceBru Apr 11 '22 at 19:26
  • The creators of the list type chose not to make it hashable (because it is mutable and has value-based equality). If you create your own class, the choice is yours. You can make a mutable class hashable if you want, and cause bugs in your program. It is your responsibility as the definer of the class. – khelwood Apr 11 '22 at 19:27
  • @khelwood, "You can make a mutable class hashable" - I just created a random mutable class, and it's already hashable, by default. "cause bugs in your program ... It is your responsibility..." - looks like Python _made_ my mutable class hashable by default and thus subjected me to possible bugs? – ForceBru Apr 11 '22 at 19:32
  • Here's a few reasons why making `list`s hashable break the mental model of how `dict` lookup is supposed to work: Suppose `list`s are hashable, then this is OK: `a = [1, 2, 3]; b = [1, 2, 3]; d = {a: 0}`. We now have `d[a] == 0`. Should we also have `d[b] == 0`? If based on IDs, no. But in that case, `d[a] == 0` should still apply even after e.g. `a.append(4)`. If not based on IDs (but on values), what happens when you mutate `a` *after* using it as a key in a `dict`? The whole thing becomes a mess. – jmd_dk Apr 11 '22 at 19:32
  • [Here](https://stackoverflow.com/a/42203997/18135454) is an answer within a related post that is insightful. Basically says that the language designers want a user to take explicit action for mutable types (such as writing their own class or subclassing a built-in mutable type like list) to make them hashable, as doing so comes with some risks that they don't want users to be exposed to by default. – constantstranger Apr 11 '22 at 19:33
  • 2
    @ForceBru To be clear, I meant the problems of a hash based on an object's mutable value. The default hash and equality are based on the object's identity. – khelwood Apr 11 '22 at 19:36

0 Answers0