---restore content starts---
Span style= "Background-color: #3366ff" > numbers and strings , &N Bsp , &NB Sp , &NB Sp , &NB Sp , &NB Sp
Both the numbers and the memory in the string point to the same address, so deep copies and shallow copies are meaningless to them.
Import Copya = 123 #赋值print (ID (a)) #输出存储变量的地址b = Aprint (ID (b)) B = Copy.copy (a) #浅拷贝print (ID (b)) C = Copy.deepcopy (a) #深拷贝print (ID (c))
Shallow copy
For dictionary tuples and lists, the address of the memory is different when a shallow copy and a deep copy are made
A shallow copy copies only the first layer of data in memory
Import copydic = {' Key1 ': 123, ' Key2 ': [123,456]} #创建一个字典嵌套列表print (ID (dic[' key1 '])) print (ID (dic[' key2 ')) print ( ID (dic[' key2 '][0])) #打印列表中的地址print ("\ n") New_dic = Copy.copy (DIC) #使用浅拷贝赋值 print ("*", ID (new_dic[' key1 ')) Print ("*", ID (new_dic[' key2 ')) print ("*", ID (new_dic[' key2 '][0]))
Find the value of an in-memory address is exactly the same
Deep Copy & nbsp , &NB Sp , &NB Sp , &NB Sp , &NB Sp , &NB Sp span>
And for a deep copy, all the data will be recreated.
Import copydic = {' Key1 ': 123, ' Key2 ': [123,456]} #创建一个字典嵌套列表print (ID (dic[' key1 '])) print (ID (dic[' key2 ')) print ( ID (dic[' key2 '][0])) #打印列表中的地址print ("\ n") New_dic = Copy.deepcopy (DIC) #使用深拷贝赋值 print ("*", ID (new_dic[' key1 ') ]) Print ("*", ID (new_dic[' key2 ')) print ("*", ID (new_dic[' key2 '][0]))
Application of deep-shade copy
In a shallow copy, the value of the copied object changes when the value of the copied object is changed.
ImportCopydic= {'Key1': 123,'Key2': [123,456]}#Create a dictionary nested listPrint(dic['Key2'][0])#Print the address in the listPrint("\ n") New_dic= Copy.deepcopy (DIC)#use a shallow copy to assign a valuenew_dic['Key2'][0] = 789#change the value of a list in a dictionaryPrint(dic['Key2'][0])Print((new_dic['Key2'][0]))
Deep copy should be used when you do not want to change the copied value
ImportCopydic= {'Key1': 123,'Key2': [123,456]}#Create a dictionary nested listPrint(dic['Key2'][0])#Print the address in the listPrint("\ n") New_dic= Copy.deepcopy (DIC)#assigning values using deep copiesnew_dic['Key2'][0] = 789#change the value of a list in a dictionaryPrint(dic['Key2'][0])Print((new_dic['Key2'][0]))
Shallow copy deep copy deep copy
---restore content ends---
Deep copy and shallow copy of Python