I was trying to do matrix multiplication, while initializing a list with a shortcut method i.e. C[[0]*column]*row. The list was initialized how i wanted but it gave me the wrong answer. After that I tried initializing the code with for loop, it gave me the correct answer. Please help me out in understanding what is the reason behind this python list behavior.
This is my code:
A = [[1,2],[3,4]]
B = [[5,6,],[7,8]]
C = []
for i in range(2):
c = []
for j in range(2):
c.append(int(0))
C.append(c)
D = [[int(0)]*2]*2
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
D[i][j] += A[i][k] * B[k][j]
for r in C:
print(r)
print(D)
This is my Output:
[[19, 22],[43, 50]]
[[62, 72], [62, 72]]