May-29-2017, 08:49 PM
May-29-2017, 09:36 PM
>>> a = [[0] * 2] * 3 >>> a [[0, 0], [0, 0], [0, 0]] >>> b = [[0,0],[0,0],[0,0]] >>> b [[0, 0], [0, 0], [0, 0]] >>> b==a True >>> a[1][1] = 5 >>> a [[0, 5], [0, 5], [0, 5]] >>> b[1][1] = 5 >>> b [[0, 0], [0, 5], [0, 0]] >>> b==a False >>>I think a[1][1] is the 1st mutlipier (originally 2)
May-29-2017, 09:37 PM
Excuse me asking but I,m newbie.
This shouldn't happen, right?
This shouldn't happen, right?
a = [[0,0]] * 3 a[1][1] = 5 a [[0, 5], [0, 5], [0, 5]]
May-29-2017, 10:23 PM
No, that's expected behavior. Lists are mutable. Python generally doesn't make copies of them, instead it makes new references to them. So you first line doesn't make three different instances of [0, 0], it makes three references to the same [0, 0]. So when you change it using one reference, all the other references show the same change.
Try:
Try:
a = [[0, 0] for dummy in range(3)]This doesn't copy the same list, it makes a new list each time it loops.
May-29-2017, 10:37 PM
>>> a = [[0,0]] * 3 >>> b = [[0,0] for i in range(3)] >>> a [[0, 0], [0, 0], [0, 0]] >>> b [[0, 0], [0, 0], [0, 0]] >>> a == b True >>> # Here "is" the clue >>> a is b False >>> [id(i) for i in a] [57010936, 57010936, 57010936] >>> [id(i) for i in b] [57074232, 56920944, 57010576]With
a = [[0,0]] * 3
you make 3 copy of list [0,0] that refer to same memory location(what id()
show)With
[[0,0] for i in range(3)]
or [[0,0], [0,0], [0,0]]
are making list that dos not refer to same memory location.When do
a = b
,both name tag to same object in memory.