0

Possible Duplicate:
Unexpected feature in a Python list of lists

I tried to create a list in python using following statement

S = [0] * 10

And it worked out well

S[0] = 1
S
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

But when I try to generate a two-dimensional list, something unexpected occurs

S = [[0] * 10] * 2
S[0][1] = 1
S[0][2] = 2
S
[[0, 1, 2, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 0, 0, 0, 0, 0, 0]]

Note that S[0] == S[1]

Why?

By the way, is this the best approach of constructing an 2d array? If not, what makes the best?

Community
  • 1
  • 1
Determinant
  • 3,886
  • 7
  • 31
  • 47
  • 2
    It's actually explained in the reference (Note 2) http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange – kennytm Oct 08 '11 at 08:54

2 Answers2

4

Because you told it to make 2 copies of the same mutable list.

S = [[0] * 10 for x in range(2)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • but why doesn't it make 10 copies of [0] when i create 1d list? – Determinant Oct 08 '11 at 08:58
  • 2
    @ymfoi - Actually, it does. But when you assign to a list item (`S[0] =`), the item is replaced with a new object. If you have a 2D list, the assignment `S[0][1] =` first **gets** the item from the first list and only then replaces an item in the second list. Since all items in the first list reference the same object, the assignment result can be seen in all of them. – yak Oct 08 '11 at 11:49
0

S = [[0] * 10] * 2 means 2 references for [[0]*10], so when your change one the other will change.By the way ,the reason why [0]*10 is fine is : a reference to a number.

Eric.Q
  • 703
  • 1
  • 9
  • 21