Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I create a list of lists and want to append items to the individual lists, but when I try to append to one of the lists (a[0].append(2)), the item gets added to all lists.

a = []
b = [1]

a.append(b)
a.append(b)

a[0].append(2)
a[1].append(3)
print(a)

Gives: [[1, 2, 3], [1, 2, 3]]

Whereas I would expect: [[1, 2], [1, 3]]

Changing the way I construct the initial list of lists, making b a float instead of a list and putting the brackets inside .append(), gives me the desired output:

a = []
b = 1

a.append([b])
a.append([b])

a[0].append(2)
a[1].append(3)
print(a)

Gives: [[1, 2], [1, 3]]

But why? It is not intuitive that the result should be different. I know this has to do with there being multiple references to the same list, but I don't see where that is happening.

like image 395
litturt Avatar asked Jun 15 '11 15:06

litturt


People also ask

Does append change the list?

append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.

What happens if you append a list to a list?

append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).

Does append add to the end of a list Python?

The append() Python method adds an item to the end of an existing list. The append() method does not create a new list. Instead, original list is changed. append() also lets you add the contents of one list to another list.

Can append take multiple values in list Python?

You can use the sequence method list. extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list.


1 Answers

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]]
like image 199
Bryan Oakley Avatar answered Oct 12 '22 23:10

Bryan Oakley