1

I want to assign value to 2d array in for loop
This is my code

num = 0
n = 3
arr = [[0] * n] * n

for i in range(n):
    for j in range(n):
        arr[i][j] = num
        num +=1

The output I expected is

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]

But actual output is

[6, 7, 8]
[6, 7, 8]
[6, 7, 8]

Is there any way to fix this?

ssabi
  • 13
  • 4
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Błotosmętek Apr 30 '20 at 18:37

1 Answers1

3
arr = [[0] * n] * n

It creates n copies of list. So, when you make a change in one list, all others are changed as well. You can change it to something like this:

arr = [[0 for j in n] for i in n]
Moosa Saadat
  • 1,159
  • 1
  • 8
  • 20