Python Forum
2-D list element assignment - 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: 2-D list element assignment (/thread-10552.html)



2-D list element assignment - ashutosh759 - May-24-2018

nm = 4
c = [[0, False]] * nm
c[0][0] = 1
print(c)
I expected that it should give an output as [0, False] (Printed 4 times). Instead, the output is [1, False](Printed 4 times).
Can anyone explain?


RE: 2-D list element assignment - scidam - May-25-2018

[x]*n -- replicates x n-times, i.e. [x]*n = [x, x, ....ntimes, x]
[0, False] is a mutable object (it is a list), so, each time it is replicated, internally, Python uses a pointer to the same object: so a target list -- [x, x, ..., x] is just a set of the same objects.
So, when you change one of them, you change all object(s) at once.

You can avoid this behavior if you define the list as follows:

z = [[0, False], [0, False], [0, False], [0, False]]

In this case, [0, False] items are internally presented as different objects,
so, if you try to change one of them, e.g. z[0][0] = 1, this willn't affect on others.