Why are tuples immutable?

Fredrik Lundh fredrik at pythonware.com
Wed Dec 15 06:20:14 EST 2004


Antoon Pardon wrote:

>> how would you implement a dictionary where the keys could change, without
>> any performance penalty compared to the current implementation?
>
> The performace gained by using tuples as keys in dictionaries is
> entirely illusional.
>
> Sure the fact that you use a tuple which is immutable, makes that
> you can put the key directly in the dictionary instead of a copy
> and that will gain you some performance.
>
> But this performance gain can be more than offset by other code
> in the program.
>
> Suppose you need a list/tuple as a key and most opperation you
> will do on those keys will be appends and pops. You now have the
> itwo choices
>
>   1) Always convert your lists to tuples on key entries
>   and keys accesses, which will mean more copying than when a
>   copy of a key would have been made on key entry.
>
>   2) Simulate appends and pops by tuple operations which can also
>   require more copying than was gained by using tuples as key

sorry, but I don't understand your reply at all.  are you saying that dictionaries
could support mutable keys (e.g lists) by making a copy of the key?  how would
such a dictionary pick up changes to the original key object?  (I'm talking about
the key stored in the dictionary, not the key you're using to look things up).

</F> 






More information about the Python-list mailing list