Constructing a two-dimensional list [duplicate]
Po开发者_运维问答ssible 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?
Because you told it to make 2 copies of the same mutable list.
S = [[0] * 10 for x in range(2)]
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.
精彩评论