Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign a value to nested list while keeping the original list in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 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 :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading