0

I am trying to initialise a new array whose first row and the first column are the same as the first array, However it is giving me a very unusual output.

arr = [[1,2,3],[4,5,6],[7,8,9]]
n = len(arr)
m = len(arr[0])
s = [[0]*n]*m
for i in range(n):
    el = arr[i][0]
    s[i][0] = el
for j in range(m):
    el = arr[0][j]
    s[0][j] = el
print(s)

The Output is [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Sai
  • 1
  • 1
    As the link shows this: `[[0]*n]*m` doesn't really work the way you are hoping. You end up with multiple references to the *same list*. So changing one, changes it everywhere. – Mark Jul 05 '21 at 21:39
  • `[[0]*n]*m` creates a list with *m* references to *the same list*, the one created by `[0]*n` – juanpa.arrivillaga Jul 05 '21 at 22:02

0 Answers0