有两种方法做Python List的浅拷贝(Shallow Copy),使用切片操作符([:])或者list创建函数,等号(=)没有做copy,并没有创建一个新的List。如下代码:
>>> list1 = [1,2,3,4]
>>> list2 = list1 # no new list created.
>>> list2
[1, 2, 3, 4]
>>> list2[0] = 5
>>> list2
[5, 2, 3, 4]
>>> list1
[5, 2, 3, 4]
>>>
>>> list3 = list1[:] # shallow copy, list3 is a new list. Equivalent to list3 = list1.copy()
>>> list3[0] = 6
>>> list3
[6, 2, 3, 4]
>>> list1
[5, 2, 3, 4]
>>>
>>> id(list1)
41114480
>>> id(list2)
41114480
>>> id(list3)
41114400
>>>
>>> list4 = list(list1) # also shallow copy.
>>> list4
[5, 2, 3, 4]
>>> id(list4)
43406200
>>> list4[0] = 7
>>> list4
[7, 2, 3, 4]
>>> list1
[5, 2, 3, 4]
>>>
浅拷贝和深拷贝各有用处,并没有谁好谁坏。深拷贝是完全重新创建了一个包含全局层次数据的新的List,这样在后续操作上可以隔离,大部分时候,浅拷贝很好用,一份数据在各个函数内都可以引用。如何坐深拷贝,请参考:Python的深拷贝和浅拷贝
使用加号(+)将两个list连接起来,也是创造一个新的list,也是浅拷贝:
>>> list6 = [1, [2,3]]
>>> list7 = [4, [5,6]]
>>> list8 = list6 + list7 # shallow copy to create a new list by concatenate two other lists.
>>> list8
[1, [2, 3], 4, [5, 6]]
>>> list8[1][0] = 9
>>> list6
[1, [9, 3]]
>>> list8[3][0] = 9
>>> list7
[4, [9, 6]]
>>>
>>> id(list6)
41114360
>>> id(list7)
41113720
>>> id(list8)
41114240
>>>
使用加号的方式做浅拷贝相对隐蔽,要注意。