I am trying to create a 2D array as such and just update single values at a time, shown here:
M = [[0]*3]*3
M[0][0] = 3
print(M)
which is returning the following:
[[3, 0 , 0], [3, 0, 0], [3, 0, 0]]
Anyone have an idea of what I've done wrong?
CodePudding user response:
What your first line is doing is creating one inner length 3 list, and adding three references of it to your outer list M. You must declare each internal list independently if you want them to be independent lists.
The following is different in that it creates 3 separate instances of your inner length 3 list:
M = [[0]*3 for _ in range(3)]
M[0][0] = 3
print(M)
CodePudding user response:
The 2D array is at the same address as the first array.
M = [[0,0,0],[0,0,0],[0,0,0]]
M[0][0] = 3
print(M)
Which is returning the following: [[3, 0, 0], [0, 0, 0], [0, 0, 0]]
FYI: Problem same as this: Why in a 2D array a and *a point to same address?