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

Creating a copy of a list that can be edited

I am trying to create a copy of a list that can be changed without changing the original list. Here is the code that I tried using slicing but it did not work:

l1=[[i,i] for i in range(4)]
l2=l1[:]
l2[2][1]=999
print('l1; ',l1)
print('l2: ',l2)

l1:  [[0, 0], [1, 1], [2, 999], [3, 3]]
l2:  [[0, 0], [1, 1], [2, 999], [3, 3]]

l2 is printed correctly. May I know what I can do so that l1 remains what it was in the definition? Thanks.

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

>Solution :

Use copy.deepcopy() since the list contains an object

import copy
l1 = [[i,i] for i in range(4)]
l2 = copy.deepcopy(l1)
l2[2][1] = 999

print('l1; ',l1)
print('l2: ',l2)

# l1;  [[0, 0], [1, 1], [2, 2], [3, 3]]
# l2:  [[0, 0], [1, 1], [2, 999], [3, 3]]
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