-1

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]]
  • The sub-lists in `D` point to the same list in memory. See https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Matt Hancock Apr 04 '20 at 23:26

1 Answers1

0

The reason is probably, that in doing the 'shortcut method' where you are multiplying lists, Python does not do a deep copy of the list. See this example:

d = [ 5 * [2] ] * 3
>> [[2, 2, 2, 2, 2], [2, 2, 2, 2, 2], [2, 2, 2, 2, 2]]

d[0][0] = 1
>> [[1, 2, 2, 2, 2], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2]]

It looked like I was just about to modify element [0][0] but in fact the other rows are just referencing the first row - so I changed three rows instead of one.

Please consider using numpy for doing matrix calculations :)

Lydia van Dyke
  • 2,466
  • 3
  • 13
  • 25