Why are tuples immutable?
apardon at forel.vub.ac.be
Tue Dec 21 16:40:08 CET 2004
Op 2004-12-21, Nick Coghlan schreef <ncoghlan at iinet.net.au>:
> 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'.
That is an implemantation detail. Likewise a dictionary is probably not
always in a sane state when a new key is inserted. The fact remains that
in a sorted list or a heap, mutating an element arbitrarily can mess up
> 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.
I could argue that this is then a failing of dictionary that doesn't
provide a method to clean up after a key is mutated.
> 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.
No it is not.
And yes I know what to do if I want to use mutable keys as objects. I'm
just argueing against those who think that should be somehow forbidden.
More information about the Python-list