Python Forum
Python list problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python list problem (/thread-3510.html)



Python list problem - bagjohn - May-29-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)



RE: Python list problem - Larz60+ - May-29-2017

>>> 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)


RE: Python list problem - bagjohn - May-29-2017

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]]



RE: Python list problem - ichabod801 - May-29-2017

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.


RE: Python list problem - snippsat - May-29-2017

>>> 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.