1
a=[[1],[2,3],[4,5,6]]
dp=[[0]*3]*3
dp[0][0]=a[0][0]
for i in range(1,3):
    for j in range(0,len(a[i])):
        if j==0:
            dp[i][j]=dp[i-1][j]+a[i][j]
for i in range(3):
    for j in range(3):
        print(dp[i][j])

Output of the program: [[7,0,0],[7,0,0],[7,0,0]]

Expected output of the program: [[1,0,0],[3,0,0],[7,0,0]]

dp[i][j]=dp[i-1][j]+a[i][j] --> why the value is not getting assigned properly, the way I expect (expected output)

I tried to print the list dp but still I am not getting the output. I tried this in online compiler.

1 Answers1

0

Python passes everything but primative data types around by reference (the data isn't copied). This affects your code where you have created the 2d array:

dp=[[0]*3]*3

If we break this down we can see what actually happens

temporaryList = [0] * 3 # [0, 0, 0]
dp = temporaryList * 3 # [<reference to temporaryList>, <reference to temporaryList>, <reference to temporaryList>]

This means if you edit a item in the first element of dp, it also edits it in all the others!
To fix this you can use list comprehension (there are many other methods on creating 2D arrays, you can look them up)

dp = [[0 for x in range(3)] for y in range(3)]

This then generates the requested output

SollyBunny
  • 800
  • 1
  • 8
  • 15
  • 1
    Minor correction: the first sentence is not correct. All data regardless of "primitive-ness" is passed "by value by reference". Integers and lists are treated identically. It just doesn't matter with immutable objects since they can't be mutated. – Carcigenicate Jun 18 '23 at 18:50
  • Not quiet sure what you mean? – SollyBunny Jun 18 '23 at 18:53
  • 1
    The "everything but primative data types" part isn't true. There is no difference. You can see that if you pass an integer into a function and check the `id` of the integer argument outside of the function and the parameter value inside the function. Both will have the same address, indicating that the integer was not copied when passed. Not really important to the answer since it was a side note anyway, but I thought it should be corrected since it's a *very* common misunderstanding. – Carcigenicate Jun 18 '23 at 18:55
  • You are correct, however the data then does get copied on edit. The fact it doesn't copy straight away is probably an optimization. – SollyBunny Jun 18 '23 at 18:57