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
  • 148
  • 1
  • 12

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
  • 567
  • 4
  • 10