0

Here is my code.

import numpy as np

m = 2
n = 2

arr = [[0]*m]*n

for i in np.arange(n):
    for j in np.arange(m):
        print(i)
        arr[i][j] = i

print(arr)

the output is:

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

I do not understand why the output array is not [[0,0],[1,1]]. Please I am losing my mind.

queste
  • 188
  • 1
  • 14
  • Have a look at this https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Jayesh Aug 01 '21 at 21:05

1 Answers1

2

Because [0]*m object is being repeated n times. Whatever your i you're changing the same object, so you see only the last change printed.

arr = [[0]*m for _ in range(n)] solves the problem

PermanentPon
  • 702
  • 5
  • 10