Add List to Set is Possible in Java but not in Python?
Lists are unhashable in python because they do not define __hash__
. There are reasons for that, but you could conceivably define your own mutable class that does, provided that said hash does not change across the lifetime of the object. For example, using id(x)
as the hash. In fact, you've probably unknowingly implemented exactly that in a lot of your own classes.
I'll quote from the docs on "hashable":
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is their
id()
.
Mutability and hashability are coupled, but not at all the same thing.