0
def main():
   w = [[0]*3] * 3
   print("original w", w)
   w[0][2] = 2
   print("new w:",w)

   k = [[0,0,0],[0,0,0],[0,0,0]]
   k[0][2] = 2
   print("new k",k)

output is:

original w [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

new w: [[0, 0, 2], [0, 0, 2], [0, 0, 2]]

new k: [[0, 0, 2], [0, 0, 0], [0, 0, 0]]

Question is why w[0][2] =2 make w change all second index not only w[0][2] but also w[1][2] and w[2][2] ? I want to change w like k ( only change [0][2])

I don't know the difference between the two lists. Thank you for letting me know my errors! Thanks!

Julia
  • 315
  • 4
  • 15
  • construct your `w` as `w = [[0 for _ in range(3)] for _ in range(3)]`. The way it is right now, your 3 sublists are actually all **the same list**. – Ma0 Oct 17 '18 at 07:02
  • @Ev.Kounis Thank you!! btw, why w = [[0]*3] * 3 make same list?? – Julia Oct 17 '18 at 07:13
  • The best answer to that you will find on the link for the duplicate question. – Ma0 Oct 17 '18 at 07:16

0 Answers0