0

I am trying to print concentric matrix. I have written the following code to print the lower half of the matrix

A=3
arr=[0]*(2*A-1)
matrix=[arr]*(2*A-1)
# print(matrix)
max=2*A-2
mid=max/2
for i in range(0,2*A-1):
    for j in range(0,2*A-1):
        if(i>=j):
            matrix[i][j]=int(i-mid+1)
            if(i<max-j):
                matrix[i][j]=int(A-j)
    print(matrix)

Output:

[[3, 0, 0, 0, 0], [3, 0, 0, 0, 0], [3, 0, 0, 0, 0], [3, 0, 0, 0, 0], [3, 0, 0, 0, 0]]
[[3, 2, 0, 0, 0], [3, 2, 0, 0, 0], [3, 2, 0, 0, 0], [3, 2, 0, 0, 0], [3, 2, 0, 0, 0]]
[[3, 2, 1, 0, 0], [3, 2, 1, 0, 0], [3, 2, 1, 0, 0], [3, 2, 1, 0, 0], [3, 2, 1, 0, 0]]
[[3, 2, 2, 2, 0], [3, 2, 2, 2, 0], [3, 2, 2, 2, 0], [3, 2, 2, 2, 0], [3, 2, 2, 2, 0]]
[[3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 3, 3, 3, 3]]

Why all the lists within the list matrix are getting changed when only the ith list should be changed.

  • 1
    Long story short, `[arr]*(2*A-1)` is creating multiple references to the same list, not multiple copies of the original list. – Carcigenicate Jul 20 '20 at 21:40
  • Use `matrix = [[0 for col in range(2*A-1)] for row in range(2*A-1)]` (as initial value before the loop) and all will be well. – alani Jul 20 '20 at 21:43

0 Answers0