Possible dupe: Append value to one list in dictionary appends value to all lists in dictionary
I've encountered a problem in using nested arrays, where all elements are updated, when I only want to append to a specific index.
x = [[]] * 6
x[0].append(1)
# expected: [[1], [], [], [], [], []]
# result: [[1], [1], [1], [1], [1], [1]]
What I'm guessing is that x[0]
returns []
, which turns the statement to [].append(1)
and updates all empty lists. This is supported by the fact that non-empty sets will not be changed.
x = [[]] * 6
x[1] = [0]
x[0].append(1)
# [[1], [0], [1], [1], [1], [1]]
I currently do this workaround to assign the value:
x = [[]] * 6
y = x[0].copy()
y.append(1)
x[0] = y
I want to understand 1) why python would evaulate the x[0]
bit and make [].append()
apply to multiple elements in the list, if my theory is correct and 2) if there is a better way to add values in a nested list.