python list - the difference between deep and shallow copy copy

Must first talk about why you need to copy the list, in order to solve the problem simple assignment, transfer addresses, because the list of assignments in the past, in fact, points to the same address, description of the problem to see the code

a = [1,2,3]
b = a
# list类型,简单赋值操作,是传地址
print(id(a))
print(id(b))
b[1] = 6
print(b)
print(a)
执行结果,输出的是:
2460317409864 
2460317409864
[1, 6, 3]
[1, 6, 3]
#同一地址,修改b的列表,a也会同时改变。

To solve this problem, list assignment requires the use of copy function

a = [1,2,3]
b = a.copy()
print(id(a))
print(id(b))
b[1] = 6
print(b)
print(a)

However, since only a shallow copy copy, one copy only which

Deep differences with shallow copy copy

# 出现下列问题的原因是,copy‘函数是个浅拷贝函数,即只拷贝一层内容
# 深拷贝需要使用copy模块
a = [1,2,3,[10,20,30]]
b = a.copy()
print(id(a))
print(id(b))
print('*' * 20)
print(id(a[3]))
print(id(b[3]))
a[3][2]=666
print(a)
print(b)
以上代码输出结果为:
2963694903944
2964112968904
********************
2963694903880
2963694903880
[1, 2, 3, [10, 20, 666]]
[1, 2, 3, [10, 20, 666]]

Then demonstrate what a deep copy

import copy
a = [1,2,3,[10,20,30]]
b = copy.deepcopy(a)  #这里不一样哦
print(id(a))
print(id(b))
print('*' * 20)
print(id(a[3]))
print(id(b[3]))
a[3][2]=666
print(a)
print(b)
#输出结果:
2620494013064
2620883635400
********************
2620494013000
2620495283144
[1, 2, 3, [10, 20, 666]]
[1, 2, 3, [10, 20, 30]]
#这才是我们想要得到的目的

Do not understand can try their own hands-on

Guess you like

Origin blog.51cto.com/14113984/2429087