Why are tuples immutable?

Nick Coghlan ncoghlan at iinet.net.au
Tue Dec 21 15:06:17 CET 2004


Antoon Pardon wrote:
> Why then doesn't python think the same about sorted lists. When I have a
> sorted list and do operations on it that depend on it being sorted,
> I can mess things up just as easily by mutating an element in that
> sorted list as I can mess things up by mutating a dictionary key.

Incorrect, and this appears to be the point where our major disagreement lies.

Mutate a value in a sorted list and you can fix that easily, just by calling its 
sort() method again (and, in fact, mutate and resort is a fairly common idiom 
for small datasets). 'sorted' and 'heapified' are list properties that are 
easily broken by direct manipulation, but are also easily restored by once again 
'sorting' or 'heapifying'.

Change the hash value of an item used as a key in a dictionary, and *the 
internal state of the dictionary is likely to broken in a manner you probably 
cannot fix*. The only reason the 'probably' is there is because you should be 
able to 'fix it' by changing the hash value back to what it was originally.

Waitasec - wouldn't it be easier if dictionaries just made it a rule that the 
hash value wasn't allowed to change? Hang on, that's exactly what they do.

Now, if all you want is a mutable container that can be used as a dictionary 
key, then inherit from list and override the comparison methods (including hash) 
to work solely by object id. Then use that container instead of list().

Or, as I suggested elsewhere in this thread, use a special KeyedById class which 
*doesn't copy anything anywhere*.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list