python: deep copy and shallow copy problem

shallow copy:

For example, now there is an A = 2, and 2 is stored in the yellow address below:

If you use B=A directly in python, it is a shallow copy operation. The code is as follows

A = 1
B = A
B = 2
print("A")#A = 2
print("B")#B = 2

When creating B=A, it is equivalent to the following operations:

On the original yellow address, an index B is added, so A and B point to the same address, modifying the value of B is equivalent to modifying the value of the address pointed to by B, so A is also modified

Deep copy:

And deep copy in python: the code is as follows

B = A.copy()

The deep copy operation is to use a new blue address to copy the content of the yellow address where A is located, and then add an index B to the blue address

Therefore, modifying the value of B is equivalent to modifying the value of the blue address, and will not affect the content of the yellow address.

A = 1
B = A.copy()
B = 2
print("A")#A = 1
print("B")#B = 2

Guess you like

Origin blog.csdn.net/weixin_53374931/article/details/129702240