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]]
I expected this to only affect the first sublist, not all of them. That is:
>>> print(xs)
[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Why did every first element of every sublist change to 5
?
See also:
How do I clone a list so that it doesn't change unexpectedly after assignment? and
How to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? 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