1

I tried making a 2d array using 2 approaches in python. Why does approach 1 provide an unexpected side effect where all the rows get updated?

dp1 = [ [0] * 5 ] * 8
dp1[2][2] = dp1[1][1] + 1

print("DP1")
for dp in dp1: print(dp)

dp2 = [[0] * 5 for _ in range(8)]
dp2[2][2] = dp2[1][1] + 1

print("DP2")
for dp in dp2: print(dp)

Output:

DP1
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]


DP2
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 1, 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]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Parth
  • 2,682
  • 1
  • 20
  • 39

0 Answers0