Why are tuples immutable?
apardon at forel.vub.ac.be
Wed Dec 15 13:24:37 CET 2004
Op 2004-12-15, Fredrik Lundh schreef <fredrik at pythonware.com>:
> 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).
You want to mutate a key that is within a dictionary?
That sounds as bad as mutating an element in a sorted list.
More information about the Python-list