Why does foo.append(bar) affect all elements in a list of lists?

It is because the list contains references to objects. Your list doesn’t contain [[1 2 3] [1 2 3]], it is [<reference to b> <reference to b>].

When you change the object (by appending something to b), you are changing the object itself, not the list that contains the object.

To get the effect you desire, your list a must contain copies of b rather than references to b. To copy a list you can use the range [:]. For example, :

>>> a=[]
>>> b=[1]
>>> a.append(b[:])
>>> a.append(b[:])
>>> a[0].append(2)
>>> a[1].append(3)
>>> print a
[[1, 2], [1, 3]]

Leave a Comment