Why are tuples immutable?

Max M maxm at mxm.dk
Thu Dec 16 05:35:42 EST 2004


Antoon Pardon wrote:

> Well IMO there are two sides in this argument. The first is whether
> or not python allows mutable keys. The second is whether or not
> limiting keys to immutables in dictionaries provides a performance
> gain.


The problem is that you don't understand what dicts are typically used 
for. Because of the nonliniarity in dict lookups, dicts are used for 
optimisation.

I actually think it's the most important tool for optimising Python code.

If dicts allowed mutable keys, a dict would need to run code that 
corresponds to::

def has_key(key):
     for key in self.keys():
         if a_key == key:
             return True
     return False

Using immutable keys, a code can be generated for the key, that can be 
efficiently stored in something like a binary tree.

This makes lookup *very much* faster, and is the speed concern that 
Python programmers care about.

Not the time taken to convert a list into a tuple.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science



More information about the Python-list mailing list