Posts: 2
Threads: 1
Joined: May 2017
Hello!
Can someone please explain what happens here???
a = [[0] * 2] * 3
b = [[0,0],[0,0],[0,0]]
print(b==a)
a[1][1] = 5
b[1][1] = 5
print(b==a)
Posts: 12,031
Threads: 485
Joined: Sep 2016
May-29-2017, 09:36 PM
(This post was last modified: May-29-2017, 09:36 PM by Larz60+.)
>>> 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)
Posts: 2
Threads: 1
Joined: May 2017
May-29-2017, 09:37 PM
(This post was last modified: May-29-2017, 09:57 PM by bagjohn.)
Excuse me asking but I,m newbie.
This shouldn't happen, right?
a = [[0,0]] * 3
a[1][1] = 5
a
[[0, 5], [0, 5], [0, 5]]
Posts: 4,220
Threads: 97
Joined: Sep 2016
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:
a = [[0, 0] for dummy in range(3)] This doesn't copy the same list, it makes a new list each time it loops.
Posts: 7,319
Threads: 123
Joined: Sep 2016
>>> 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.
|