Why are tuples immutable?

Roy Smith roy at panix.com
Wed Dec 15 17:07:47 CET 2004


Jp Calderone  <exarkun at divmod.com> wrote:
>  Dictionaries support mutable keys just find.  What they don't 
>support is unhashable keys.  
>
>  For some objects, this is an important distinction: lists are 
>mutable but not hashable.

Of course, you could subclass list to make a mutable, hashable list:


class HashableList (list):
    def __hash__ (self):
        return sum (self)

myList = HashableList ((1, 2, 3))

d = {myList: "fred"}

print d
print d [myList]

myList.append (0)
print d [myList]

myList.append (42)
try:
    print d [myList]
except KeyError:
    print "didn't work because the hash changed"



More information about the Python-list mailing list