2

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114
Garfield
  • 182
  • 7

1 Answers1

2

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]]
user2314737
  • 27,088
  • 20
  • 102
  • 114