Why are tuples immutable?

Nick Coghlan ncoghlan at iinet.net.au
Mon Dec 13 07:37:22 EST 2004


jfj wrote:

> Enlighten me.

.>>> x = ()
.>>> y = ()
.>>> x is y
True
.>>> x = []
.>>> y = []
.>>> x is y
False
.>>> x = range(100000)
.>>> y = tuple(x) # Makes a copy
.>>> z = tuple(y) # No need to make a copy
.>>> x is y
False
.>>> y is z
True

Immutable objects can use optimisation tricks that mutable objects can't rely 
on. So, no, a 'mutable tuple' of any description would not be as fast as the 
current tuple implementation.

If you want numbers to look at, try some timings comparing the following class 
to the builtin tuple:

.   _tuple = tuple
.   class tuple(_tuple): pass

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list