Deep copy
1. Numbers and strings
For numbers and strings, there is no actual change in assignment, shallow copy, and deep copy, because after these operations, the number or string still points to the same memory address.
import copy
# ######### 数字、字符串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 赋值 ##
n2 = n1
print(id(n2))
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))
# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))
2. Other basic data types
For dictionaries, ancestors, and lists, the memory address changes are different when assigning, shallow copying and deep copying.
1. Assignment
Assignment just creates a variable that points to the original memory address, such as:
n1 = {
"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n2 = n1
2. Shallow copy
Shallow copy, only the first layer of data is created in memory
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import copy
n1 = {
"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n3 = copy.copy(n1)
3. Deep copy
Deep copy, recreate all the data in the memory (excluding the last layer, namely: python internal optimization of strings and numbers)
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import copy
n1 = {
"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n4 = copy.deepcopy(n1)