An object that is hashable needs a __hash__
method and it has a hash value which never changes during its lifetime.
Python lists are not hashable for reasons that I totally ignore and I wonder if the following implementation is OK or if it has some glitches that I am not aware of.
class L(list):
def __hash__(self):
return id(self)
a = range(10)
l = L(range(10))
print a
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print l
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
hash(l)
>> 41889288
hash(a) # unsurprisingly it returns an error because a list is not hashable
>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
# lets append a value to l
l.append(1000)
print l
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]
isinstance(l, list) # to double check whether l is a List instance
>> True
D = {}
D[l] = "this is a dict with a list as key"
print D
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]: 'this is a dict with a list as key'}
# lets append another value to l
l.append(-10)
print D
>> {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, -10]: 'this is a dict with a list as key'}
# now lets add a normal list to the dict to the dict
D[a] = "Add a list as key"
>>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
So this a hashable list implementation that is pretty much working with no issues and I don't see why a list can't be hashable in the normal Python distribution even though it is still mutable.
NB :This question is not about why a list can't be used as a dictionary key Any explanation?