Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to 2D lists in Python [duplicate]

Tags:

python

list

I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible.

I've created an empty 2D list

listy = [[]]*3  print listy  [[], [], []] 

The following works as I'd expect:

listy[1] = [1,2] yields [[], [1,2], []]

listy[1].append(3) yields [[], [1,2,3], []]

However, when I append to one of the empty lists, python appends to ALL of the sublists, as follows:

listy[2].append(1) yields [[1], [1,2,3], [1]].

Can anyone explain to me why this behavior occurs?

like image 953
David M Avatar asked Oct 12 '11 19:10

David M


People also ask

Can you append to a 2D list in Python?

Use the append() Function to Append Values to a 2D Array in Python. In this case, we will use Lists in place of arrays. The list is one of the four built-in datatypes provided in Python and is very similar to arrays. NumPy arrays can be converted to a list first using the tolist() function.

Can I append a list to a list Python?

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).


2 Answers

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)] 

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)] >>> listy[1] = [1,2] >>> listy [[], [1, 2], []] >>> listy[1].append(3) >>> listy [[], [1, 2, 3], []] >>> listy[2].append(1) >>> listy [[], [1, 2, 3], [1]] 
like image 170
Mark Byers Avatar answered Sep 30 '22 10:09

Mark Byers


[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = [] listy = [a, a, a] 

In other words, all three list references refer to the same list instance.

like image 37
recursive Avatar answered Sep 30 '22 10:09

recursive