Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing lists inside list in Python

When I define a list in a "generic" way:

>>>a=[[]]*3
>>>a
[[],[],[]]

and then try to append only to the second element of the outer list:

>>>a[1].append([0,1])
>>>a
[[[0,1]], [[0,1]], [[0,1]]]

it appends to all elements of the outer list as can be seen above, probably due to the fact that the elements are references to the same list and not different lists (why does it work that way?). How can I actually create a list in the same "generic" way, such that the inner lists would be different lists and not just references. Thanks.

like image 913
jazzblue Avatar asked May 13 '13 21:05

jazzblue


1 Answers

You are correct, they are all references to one list.

[[] for _ in range(3)]

is a common way to create a list of independent empty lists. You can use xrange on Python 2.x, but it won't make a difference if the length is actually as small as in your example.

Not sure how to explain the reason for this (the reason is that it's implemented this way), but you can see that this behavior is documented (at least in passing) here:

Operation       Result                              Notes
s * n, n * s    n shallow copies of s concatenated  (2)

The word "shallow" here means exactly that: the elements are copied by reference. "Note 2" at the linked page also answers your question.

like image 75
Lev Levitsky Avatar answered Nov 14 '22 23:11

Lev Levitsky