深、浅拷贝

拷贝是对于可变对象list而言的,非容器类型(如数字、字符串、和其他’原子’类型的对象)是没有拷贝这个说法的

赋值

1
2
3
4
>>> a = [1,2,3,[4,5]]
>>> b = a
>>> a is b
True

b是a的别名,指向一个地址

浅拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> b = a[:]              #或者使用 b = list(a)
>>> a is b
False
>>> a[0] is b[0]
True
>>> b.append([6,7])
>>> b
[1, 2, 3, [4, 5], [6, 7]]
>>> a
[1, 2, 3, [4, 5]]
>>> b[3].append('x')
>>> b
[1, 2, 3, [4, 5, 'x'], [6, 7]]
>>> a
[1, 2, 3, [4, 5, 'x']]

浅拷贝构造了一个新的list对象
b的内部元素是a元素的引用 ( the new list represents a sequence of references to the same elements as in the first )
修改b中的可变对象会影响a ;

深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> import copy
>>> b=copy.deepcopy(a)
>>> a is b
False
>>> b
[1, 2, 3, [4, 5, 'x']]
>>> a
[1, 2, 3, [4, 5, 'x']]
>>> b[3].pop()
'x'
>>> b
[1, 2, 3, [4, 5]]
>>> a
[1, 2, 3, [4, 5, 'x']]

不仅list对象是新的,list里的元素也是新的;
这里a[3] is not b[3] .