python direct assignment, shallow vs. deep copy

1. For simple list structure

Direct assignment simply references to the same object

Shallow vs. deep copy point to different objects (simple as deep and shallow copy results copy action)

import copy

a = [1,2,3,4,5]
b = a
c = a.copy()
d = copy.deepcopy(a)
print(a,b,c,d)

# [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

a.append(6)
print(a,b,c,d)

# [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

 

2. For complex structures

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

 

Guess you like

Origin www.cnblogs.com/shnuxiaoan/p/11130911.html