how are strings immutable in python?

"Martin v. Löwis" martin at v.loewis.de
Mon Jul 7 00:53:47 EDT 2008


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

For lists, mutability is fairly natural.

Suppose you have a function f that copies
some items from one list to another. You write it
as

def f(src, dst):
    for x in src:
        if condition(x):
            dst.append(x)

If dst was immutable, an .append method could not
be defined (since it modifies the list itself), so
you would have to write

            dst = dst + [x]

However, that would only modify the local variable
dst in the function f - the parameter of the caller
of f would not get modified.

The same holds for many other operations on lists.
You can pass very complex data structures around
(lists of lists of dictionaries etc), and have functions
modify the lists, rather than creating new ones.

For example, to change a two-dimensional matrix
(which is a list of lists), you can write

   M[10][11] = 3.14

whereas with immutable lists, you would have to write

   M_10_new = M[10][:11] + [3.14] + [M10][12:]
   M = M[:10] + [M_10_new] + M[11:]

HTH,
Martin



More information about the Python-list mailing list