0

Here's a 3*4 matrix represented by embedded list, when I try to assign the dp[0][0][0] = 1, it changes all first value of each list element.

I'm using python 3.7, don't know where's the problem.

I want to change the first value of first [0,0,0,0] to 4

dp = [[[0,0,0,0]] * 3] *4
dp[0][0][0] =4
print(dp)

output like this

[[[4, 0, 0, 0], [4, 0, 0, 0], [4, 0, 0, 0]], [[4, 0, 0, 0], [4, 0, 0, 0], [4, 0, 0, 0]], [[4, 0, 0, 0], [4, 0, 0, 0], [4, 0, 0, 0]], [[4, 0, 0, 0], [4, 0, 0, 0], [4, 0, 0, 0]]]
desmaxi
  • 293
  • 1
  • 13
  • 1
    You should use `[[[0, 0, 0] for _ in range(3)] for _ in range(4)]` so that the lists are re-evaluated each time. Multiplying lists in this way will not clone the list, only create 2 references to the same object. – N Chauhan May 22 '19 at 09:30

1 Answers1

1

You do it like this :

dp = [[[0,0,0,0] for y in range(3)] for i in range(4)]
dp[0][0][0] =4
print(dp)

Output:

[[[4, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

Have a good day !

PAYRE Quentin
  • 341
  • 1
  • 12