I created a list of lists:
>>> xs = [[1] * 4] * 3 >>> print(xs) [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Then, I changed one of the innermost values:
>>> xs[0][0] = 5 >>> print(xs) [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
Why did every first element of each sublist change to 5?
See also:
-
How do I clone a list so that it doesn't change unexpectedly after assignment? for workarounds for the problem
-
List of dictionary stores only last appended value in every iteration for an analogous problem with a list of dicts
-
How do I initialize a dictionary of empty lists in Python? for an analogous problem with a dict of lists
When you write
[x]*3you get, essentially, the list[x, x, x]. That is, a list with 3 references to the samex. When you then modify this singlexit is visible via all three references to it:To fix it, you need to make sure that you create a new list at each position. One way to do it is
which will reevaluate
[1]*4each time instead of evaluating it once and making 3 references to 1 list.You might wonder why
*can’t make independent objects the way the list comprehension does. That’s because the multiplication operator*operates on objects, without seeing expressions. When you use*to multiply[[1] * 4]by 3,*only sees the 1-element list[[1] * 4]evaluates to, not the[[1] * 4expression text.*has no idea how to make copies of that element, no idea how to reevaluate[[1] * 4], and no idea you even want copies, and in general, there might not even be a way to copy the element.The only option
*has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.In contrast, a list comprehension reevaluates the element expression on every iteration.
[[1] * 4 for n in range(3)]reevaluates[1] * 4every time for the same reason[x**2 for x in range(3)]reevaluatesx**2every time. Every evaluation of[1] * 4generates a new list, so the list comprehension does what you wanted.Incidentally,
[1] * 4also doesn’t copy the elements of[1], but that doesn’t matter, since integers are immutable. You can’t do something like1.value = 2and turn a 1 into a 2.