lst1 = [11, 22, 33, 44] lst2 = lst1
print(id(lst1)) # 1916361712712
print(id(lst2)) # 1916361712712 lst1.append("hello") print(lst1) # [11, 22, 33, 44, 'hello'] print(lst2) # [11, 22, 33, 44, 'hello']
dic1 = {"name": "Tom", "age": 18} dic2 = dic1
print(id(dic1)) # 2020711820888
print(id(dic2)) # 2020711820888
dic1["hobby"] = "football" print(dic1) # {'name': 'Tom', 'age': 18, 'hobby': 'football'} print(dic2) # {'name': 'Tom', 'age': 18, 'hobby': 'football'}
對於list,set,dict來講,變量1 = 變量2,其實就至關於把變量2內容的內存地址交給變量1,並非複製一分內容,因此一變,都變。 app
lst1 = [11, 22, 33] lst2 = lst1[:] print(id(lst1)) # 1744651035720 print(id(lst2)) # 1744651035848 lst1.append(44) print(lst1) # [11, 22, 33, 44] print(lst2) # [11, 22, 33]
lst1 = [11, 22, 33, [44, 55]] lst2 = lst1.copy() print(id(lst1)) # 2081315824712 print(id(lst2)) # 2081316649864 lst1[3].append("hello") print(lst1) # [11, 22, 33, [44, 55, 'hello']] print(lst2) # [11, 22, 33, [44, 55, 'hello']]
深拷貝方法:spa
import copy s2 = copy.deepcopy(s1)
import copy lst1 = [11, 22, 33, [44, 55]] lst2 = copy.deepcopy(lst1) print(id(lst1)) # 1236356428872 print(id(lst2)) # 1236356430152 lst1[3].append("hello") print(lst1) # [11, 22, 33, [44, 55, 'hello']] print(lst2) # [11, 22, 33, [44, 55]]