bella
bella

Reputation: 33

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

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?

Upvotes: 3

Views: 1485

Answers (2)

Hoog
Hoog

Reputation: 2298

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]]

Upvotes: 5

Leo Hung
Leo Hung

Reputation: 11

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?

Upvotes: 0

Related Questions