'How to assign a value to nested list while keeping the original list in python [duplicate]

I am having two strange problems with python.

First of all, when I assign a value to a nested list like foo[0][0] = 1, foo is changed to [[1, 0, 0], [1, 0, 0], [1, 0, 0]].

Secondly, even when I use .copy(), it assigns the same thing to the original value.

>>> foo = [[0]*3]*3
>>> bar = foo.copy()
>>> bar[0][0] = 1
>>> bar
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>> foo
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

I need bar to be changed to [[1, 0, 0], [0, 0, 0], [0, 0, 0]] instead, and for foo to stay the same.

How can I do this?



Solution 1:[1]

Use deepcopy instead, and don't initialise your lists with [[x]*n]*n:

import copy
foo = [[0 for _ in range(3)] for _ in range(3)]
bar = copy.deepcopy(foo)
bar[0][0] = 1
print(foo)
print(bar)

Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1