0

What is the diference between defining with dp = [[0]*8]*8 and dp2 = [([0]*8) for i in range(8)] ? They seem to be equal but when I set one value in one case and the other they set it diferently. Why ? Thanks

>>> dp = [[0]*8]*8
>>> dp
[[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, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>> dp2 = [([0]*8) for i in range(8)]
>>> dp2
[[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, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>> dp[1][4] = 1
>>> dp2[1][4] = 1
>>> dp
[[0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 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], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>> 
limbosky
  • 11
  • 2

1 Answers1

0

They are not equal

dp = [[0]*8]*8 here there is only one inner list obejct. It's like below

a=[0]*8
dp=[a,a,a,a,a,a,a,a]

That's why when you change item in dp[1] all others are changed. There is only one inner list. dp holds multiple refereces for that same list object.

dp2 = [([0]*8) for i in range(8)] here multiple inner list objects are created. It's like below,

dp2=[[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8]

That's why you can change only 1 element without affecting others

Chamod
  • 587
  • 2
  • 6
  • 17