the trick is:
IPython prompt:
In [1]: A = [ [] ] * 2
In [2]: A
Out[2]: [[], []]
In [3]: A[0].append(1)
In [4]: A
Out[4]: [[1], [1]]
Obvious, it's not my expected result, what's I want is [[1], []]
. So why? I found no ref in the docs about python multiply sequence.
And is there any elegant(use no any explicit loop) ways to do that?
A = [ [] ] * 2
creates a list with two references to the same list:
>>> A = [ [] ] * 2
>>> id(A[0])
24956880
>>> id(A[1])
24956880
>>> id(A[0]) == id(A[1])
True
>>>
Instead, you need to use a list comprehension:
>>> A = [[] for _ in xrange(2)]
>>> A
[[], []]
>>> A[0].append(1)
>>> A
[[1], []]
>>>
Note that, if you are on Python 3.x, you will need to replace xrange
with range
.