python中的赋值与拷贝(浅拷贝与深拷贝)

时间:2022-06-03 19:48:42

1.赋值与拷贝

直接赋值(b=a)是传引用,b改动a也会改动.

a = [1, 2, 3, 4]
b = a
b[1] = 999
print(a, b)
#[1, 999, 3, 4] [1, 999, 3, 4]

 

b=a.copy()或者b=a[:]是传值,b改动不影响a.

a = [1, 2, 3, 4]
b = a.copy()
b[1] = 999
print(a, b)
#[1, 2, 3, 4] [1, 999, 3, 4]
a = [1, 2, 3, 4]
b = a[:]
b[1] = 999
print(a, b)
#[1, 2, 3, 4] [1, 999, 3, 4]

 

2.浅拷贝与深拷贝


b=a.copy()和b=a[:]都是浅拷贝,也就是只有第一层是拷贝(传值),更深的层还是传引用.

copy模块的deepcopy函数可以实现深拷贝(每一层都是传值).

import copy

a = [1, 2, 3, [1, 2, 3]]
c = copy.deepcopy(a)
c[3][1] = 999
print(a, c)
#[1, 2, 3, [1, 2, 3]] [1, 2, 3, [1, 999, 3]]

b = a[:]
b[3][1] = 999
print(a, b)
#[1, 2, 3, [1, 999, 3]] [1, 2, 3, [1, 999, 3]]