Updating 2D Array Values in Python – Updating whole column wrong?

Question:

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?

Asked By: bella

||

Answers:

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 inner length 3 lists:

M = [[0]*3 for _ in range(3)]
M[0][0] = 3
print(M)

OUTPUT

[[3, 0, 0], [0, 0, 0], [0, 0, 0]]
Answered By: Hoog

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?

Answered By: Leo Hung
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.