0

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?

1 Answers1

3

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]]
Nin17
  • 2,821
  • 2
  • 4
  • 14