python copy

Time:2020-6-19

Python copy is divided into deep copy and shallow copy

  • The shallow copy does not copy the sub object, the deep copy copies all
l1 = [1, 2, [3, 4]]
l2 = copy.copy(l1)
l1.append(5)
L1 [2]. Append (5) sub object change
print(l1)
print(l2)
--------------
[1, 2, [3, 4, 5], 5]
[1, 2, [3, 4, 5]]
  • Deep copy is two completely unrelated objects
 
l1 = [1, 2, [3, 4]]
l2 = copy.deepcopy(l1)
l1.append(5)
l1[2].append(5)
print(l1)
print(l2)
--------------
[1, 2, [3, 4, 5], 5]
[1, 2, [3, 4]]

 

This article was first published in the python black hole network, and the blog Park was updated synchronously