1

I am trying to replace values in a 2 dimensional array by accessing values in another array. Last line of my array is repeated even at places where I did not replace it.

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
AA = [[0] * (len(A)+2)] * (len(A)+2)
print(AA)
for r in range(len(A)):
    for c in range(len(A[r])):
        AA[r+1][c+1] = A[r][c]
        print(AA[r+1][c+1], " ")

print(AA)

I expect an output like:

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

But actual output is:

[[0, 7, 8, 9, 0], [0, 7, 8, 9, 0], [0, 7, 8, 9, 0], [0, 7, 8, 9, 0], [0, 7, 8, 9, 0]]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
NewToGo
  • 83
  • 5
  • 2
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Carcigenicate Aug 04 '19 at 20:04
  • Yes that is the case. Thanks Carcigenicate. – NewToGo Aug 04 '19 at 20:48

1 Answers1

0

The guilty is your AA declaration. It's not a good way to declare a list by duplicating the elements (not creating a proper matrix). More details in this discussion.

Try:

AA = [[0 for _ in range(len(A)+2)] for _ in range(len(A) + 2)]

Instead of:

AA = [[0]*(len(A)+2)]*(len(A)+2)

And that should work fine !

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40