Why are tuples immutable?

Antoon Pardon apardon at forel.vub.ac.be
Wed Dec 15 11:34:22 CET 2004


Op 2004-12-13, Fredrik Lundh schreef <fredrik at pythonware.com>:
> "jfj" wrote:
>
>> Why can't we __setitem__ for tuples?
>
> http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
>
>> The way I see it is that if we enable __setitem__ for tuples there
>> doesn't seem to be any performance penalty if the users don't use it
>> (aka, python performance independent of tuple mutability).
>
> 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.


-- 
Antoon Pardon



More information about the Python-list mailing list