A simple understanding of shallow copy copy and deep copy deepcopy in Python

  • 2021-01-06 00:40:28
  • OfStack

The following is a personal explanation of Python deep and shallow copy, easy to bypass the complex Python data structure storage to understand!

In high-level languages, variables are abstractions of memory and its addresses. Python's one-tangent variables are all objects. Variables are stored in the way of reference semantics. What is stored is only the address information corresponding to the value of a variable. Each initialization (assignment) of a variable assigns the address of the new content to the variable. Complex data structures store the worthy locations of each element. The id of the data itself is not changed when the operation such as adding, deleting and modifying is carried out. The address reference of each element is changed. If you change any variable with the same id, other variables with the same id will change accordingly. copy.copy (object), which copies the address reference of the nested structure. When the nested structure changes, the shallow copy changes accordingly. copy.deepcopy(object), completely replicates the data associated with the variable! It is no longer related to other operations!

Example:


import copy
li = [4,5]
lts = [1,2,3,li]
lt_copy= copy.copy(lts)
lt_deepcopy = copy.deepcopy(lts)
lts.append(6)
lt_copy.append(7)
print(lts,lt_copy)  # The output [1, 2, 3, [4, 5], 6] [1, 2, 3, [4, 5], 7]
li.append(8)     # The inner table li insert 
print(lts,lt_copy,lt_deepcopy)
# The output [1, 2, 3, [4, 5, 8], 6] [1, 2, 3, [4, 5, 8], 7] [1, 2, 3, [4, 5]]
# You can see that when it's right li Operation, lt_deepcopy Is not affected !

conclusion


Related articles: