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