Why are tuples immutable?

Antoon Pardon apardon at forel.vub.ac.be
Thu Dec 16 09:36:47 CET 2004

Op 2004-12-16, Jeff Shannon schreef <jeff at ccvcorp.com>:
> Antoon Pardon wrote:
>>Demanding that users of dictioanaries somehow turn their mutable objects
>>into tuples when used as a key and back again when you retrieve the keys
>>and need the object [...]
> But, you generally don't "retrieve" _keys_ from dicts.  You *use* keys 
> to retrieve *values* from a dict.  The only way to get a dict to give 
> you a key is by using the keys() method (or items() method) to give you 
> *all* of the keys. 
> You say that mutating the keys inside of a dict is bad, and yet you want 
> keys to be mutable.

1) I don't want them to be mutable. If there was a way to mark
individual objects as immutable, I wouldn't mind having all
the keys in a dictionary so marked. But I do have objects
that turn out to be mutable which are IMO usefull as keys
in a dictionary, although I don't want to mutate the keys
in dictionaries.

> This seems to be an internally inconsistent position,

That is because you didn't accurately presented it.

> nevermind the fact that I can't think of a case where I'm 
> likely to "retrieve" a key from a dict, modify it, and then put it 
> back.  (I can think of endless cases where I'd want to do that with 
> *values*, but not with keys...)

Well neither can I, but yet the fact that lists are mutable and tuples
are not, is frequently presented as reason why tuples are allowed as
keys and tuples are not.

> (And if dicts were somehow changed so that keys were copied when added 
> to a dict, just so that every once in a while someone might be able to 
> avoid a few conversions to/from tuple, then you're adding the overhead 
> of an object copy to *every* dict insertion, thus slowing down (possibly 
> by a significant amount) a large proportion of Python operations.  How 
> is that a gain?)

Well will look at two scenario's. In each we will work with mutable
objects that we would like to use a keys. In the first we transform
them into an immutable object, in the second we just allow mutables to
be inserted as keys, but insert a copy of the key instead of the key
itself in order to protect the programmer somewhat from mutating
dictionary keys.

Now in scenario one we will have a lot more copies then in scenario
two, because each time we want to use an object as a key we will
first have to transform it into an immutable. That means every
addition to the dictionary as well as every key access and each
such transform means a copy.

In scenario two we will only make a copy when a key is added to
the dictionary, we don't need to make copies with key accesses.

I think scenario two is a performance gain over scenario one.

Antoon Pardon

More information about the Python-list mailing list