Initialize a matrix (that is, a list of lists) in Python

时间:2016-04-04 18:46:00

标签: python list

I wish to initialize a list of lists using something like [[0]*n]*n. But something happened that I don't quite understand -- see the interactive iPython session below for my problem:

    In [1]: a=[[0]*3]*3

In [2]: a
Out[2]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [3]: a[1][1]=3

In [4]: a
Out[4]: [[0, 3, 0], [0, 3, 0], [0, 3, 0]]

==> WHY setting a[1][1] resulted in the above? (That is, it is setting the whole COLUMN to 3)

In [5]: b=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [6]: b
Out[6]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [8]: b[1][1]=3

In [9]: b
Out[9]: [[0, 0, 0], [0, 3, 0], [0, 0, 0]]

==> That is working fine!

0 个答案:

没有答案