Deep copy vs shallow copy of python object

The following operations will cause a shallow copy

  • Use slice[:] operations
  • Use factory functions (like list/dir/set)
  • Use the copy() function from the copy module

For elements in an object, a shallow copy will only use the reference (memory address) of the original element

import copy
class Copy_Test(object):
    def __init__(self,a):
        self.a = a

a = Copy_Test('AAA')
c = a   #Add a reference to this object 
print (id(a),id(c))   #The same memory address 
list1 = [1,2,3,4,5,6,7,8,9 ]
list2 = list1[:] #Slice copy, 2 addresses
list2[2] = 8899
print (list1,list2)   # list2 is changed list no change 
print (id(list1),id(list2)) #memory address is different 
list3 = [1,2,3,4,5,6,[7,8, 9 ]]
list4 = list3[:]
 print (id(list3),id(list4)) #The memory addresses are different
list4[6][1] = 88
print (list3,list4) #Because there are sublists, list4 is changed, and list3 will also be changed 
list5 = [8,[9,8,9 ]]
list6 = copy.copy(list5)
list6[ 1][1] = 88
 print (id(list5),id(list6)) #The memory addresses are different 
print (list5,list6) #Because copy is a shallow copy, list6 is changed, and list5 will also change 
list7 = [8,8,9,456,8,[8,946,8 ]]
list8 = copy.deepcopy(list7)
list8[ -1][1] = 888
 print (id(list7),id(list8)) #The memory address is different 
print (list7,list8) #Because copy is a deep copy, list6 is changed, and list5 will also change

For the elements in the object, the deep copy will regenerate a copy (there are special cases, which will be explained below), instead of simply referencing the memory address of the original element

Non-container types (such as numbers, strings, and other 'atomic' types of objects) are not copied

If the tuple variable contains only atomic type objects, it cannot be deep copied, see the following example

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325084991&siteId=291194637