0

My purpose was to make 2D list by *

list2 = [[False]*2]*3 #[[False,False],[False,False],[False,False]]
list3 = [[False]*2 for _ in range(3)] #same as list2
list2[0][0] = True # [[True, False], [True, False], [True, False]]
list3[0][0] = True # [[True, False], [False, False], [False, False]]

list3 works well but list2 doesn't. list2 is affected by 'x' of list2[z][x].

What happened?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
goguma
  • 1
  • 2

1 Answers1

0

* operator concats the list and makes same replica or reference of the list so change made at one place will get replicated at all places whereas for _ range(3) will evaluate one by one hence making just one change at position list[0][0]

think-maths
  • 917
  • 2
  • 10
  • 28