一、引言
在python中,對象賦值實際上是對象的引用。當創建一個對象,然后把它賦給另一個變量的時候,python並沒有拷貝這個對象,而只是拷貝了這個對象的引用
針對該列表l1=['a','b','c',['d','e','f']]
一般有三種方法,分別為:拷貝(賦值)、淺拷貝、深拷貝
注意:拷貝/淺拷貝/深拷貝都是針對可變類型數據而言的
1.1、可變or不可變
id不變值可變,即在原值的基礎上修改,則為可變數據類型;值變id也變,即重新申請一個空間放入新值,則為不可變數據類型。
age = 19
print(f'first:{id(age)}')
age = 20
print(f'second:{id(age)}')
first:4384901776
second:4384901808
二、拷貝
如果l2是l1的拷貝對象,則l1內部的任何數據類型的元素變化,則l2內部的元素也會跟着改變,因為可變類型值變id不變。
l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = l1
l1.append('g')
print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
三、淺拷貝
如果l2是l1的淺拷貝對象,則l1內的不可變元素發生了改變,l2不變;如果l1內的可變元素發生了改變,則l2會跟着改變。
import copy
l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.copy(l1)
l1.append('g')
print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')
print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f', 'g']]
四、深拷貝
如果l2是l1的深拷貝對象,則l1內的不可變元素發生了改變,l2不變;如果l1內的可變元素發生了改變,l2也不會變,即l2永遠不會因為l1的變化而變化。import copy
l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.deepcopy(l1)
l1.append('g')
print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')
print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]