how are strings immutable in python?

Delaney, Timothy (Tim) tdelaney at avaya.com
Sun Jul 6 21:00:20 EDT 2008


ssecorp wrote:

> so why would you ever want mutability?
> 
> 
> seems very counterintuitive and unreliable.

Because immutability imposes a lot of restrictions and performance
characteristics that mutable objects don't have. For example, compare
building up a list and a tuple element-by-element (using the most
appropriate methods for each):

a = []
b = ()

for i in range(10):
    a.append(i)
    b += (i,)

The list can simply grow its memory space and assign the new element.
OTOH, we need to create two new tuples each time (the one containing the
new element, and the one which is a concatenation of the old elements
plus the new element). The old tuple and the temporary tuple then get
thrown away.

Even if you optimise away the temporary 1-tuple (which python doesn't)
the need to allocate a new tuple every time and copy the old elements to
it results in much worse time and memory usage.

There are optimisations that can be done if the compiler/runtime system
can determine that there is only one reference to the immutable object
(python now does this in some cases for string concatenation), but in
general you cannot rely on this and have to assume that the worst case
applies.

Tim Delaney



More information about the Python-list mailing list