1

So I am trying to make a jagged array just like in other languages like C#, Java.

I tried using this code

array = [[0] * 5] * 5
print(list(array))

Which gave this output

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

Which is great!


But the issue is when I try to modify a value in this array, all the arrays get modified. Here is the code:

array = [[0] * 5] * 5
array[2][3] = 5
print(list(array))

And this is the output

[[0, 0, 0, 5, 0], [0, 0, 0, 5, 0], [0, 0, 0, 5, 0], [0, 0, 0, 5, 0], [0, 0, 0, 5, 0]]

What I was hoping for is something similar to this

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 5, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Any idea why this value assignment is happening to all the arrays?

martineau
  • 119,623
  • 25
  • 170
  • 301

0 Answers0