Python Forum

Full Version: Python list problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
>>> 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)
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]]
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.
>>> 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.