Python is copied and the copy depth

Assignment

Shall be assigned. For example

a = 147147
b = a # 赋值
print(a is b) # True

Conclusion: = are the same with an address number assigned numbers and strings used in the memory of them to pass.

Shallow copy

For shallow copy, dictionaries, lists, and other types of tuples, they address only the copy of the first layer

import copy

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 678]}
n3 = copy.copy(n1)  # 浅拷贝
print("第一层字典的内存地址:")
print(id(n1))
print(id(n3))
print("第二层嵌套的列表的内存地址:")
print(id(n1["k3"]))
print(id(n3["k3"]))

result

第一层字典的内存地址:
6516024
6516096
第二层嵌套的列表的内存地址:
36995720
36995720

n1 and n3 first layer at the memory address has changed, but the list of the second layer does not copy the success, it's still the same memory address, so when the list n3 of the second layer is modified, where n1 the list will be modified.

Principle is as follows

Deep copy

deepcopy

import copy

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 678]}
n4 = copy.deepcopy(n1)  # 深拷贝
print("第一层字典的内存地址:")
print(id(n1))
print(id(n4))
print("第二层嵌套的列表的内存地址:")
print(id(n1["k3"]))
print(id(n4["k3"]))

result:

第一层字典的内存地址:
31157560
35463600
第二层嵌套的列表的内存地址:
35947144
35947336

Conclusion: The memory address has changed, there are several layers of nested layers of nested changed, a copy of the very fast hardware, the value of which is referenced n1 of the
principle is as follows:

Guess you like

Origin www.cnblogs.com/jhpy/p/12045253.html