0
  cost = [[-1]*2]*2
  matrix = [[2,3],[4,5]]
  for i in range(2):
      for j in range(2):
           if i == 0:
               cost[i][j] = matrix[i][j]        
  print(cost)

I am expecting output [[2,3],[-1, -1]], but the actual output is [[2, 3],[2,3]]. I am not understanding that why are second-row elements are getting changed along with the first row?

  • Because when you do `cost[i][j] = matrix[i][j]` and then change cost it will qutomatically change matrix, it is the wrong way to have different output. Its better to print 2 different variables without any assignment operator (=) –  Mar 28 '20 at 09:22
  • `cost = [[ -1 for _ in range(2)] for _ in range(2)]` might help as it creates different inside lists and not adds the same listreference multiple times - yours adds the same reference multiple times and all references point to the same internal data. changing data is reflected over all references – Patrick Artner Mar 28 '20 at 09:29
  • Thanks @PatrickArtner. It is giving the expected output after changing the code. – Avinash Gaur Mar 28 '20 at 09:35

0 Answers0