0

when I initialize an array in python like so and then assign an element to a different value and then print out the 2d list

dist = [[0]*3]*3
dist[1][1] = 1

It gives me this

[[0,1,0],[0,1,0],[0,1,0]]

Can someone explain to me why the whole column has changed instead of just the specific element?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

1 Answers1

-1

Because each of your 3 columns are references to the same object.

If you had created dist like so:

dist = [[0,0,0],[0,0,0],[0,0,0]]

you would see the behavior you expect.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101