Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 241
bella Avatar asked Aug 04 '26 16:08

bella


1 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]]
like image 111
Hoog Avatar answered Aug 06 '26 06:08

Hoog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!