DAY 10
0

## 前言

``````#%% list copy pass by reference
a = [1,2,3]
a_ref = a
a.append(4)
print("a: ", a)
print("a_ref: ", a)
``````

1. a, a_ref 是完全相同的
2. a 和 a_ref 的記憶體位置相同
3. 故 a_ref 只是 a 的引用
4. 對 a 做修改，a_ref 也會被改變

## 淺複製與深複製 Shallow copy and deep copy

• 淺複製僅複製容器中元素的地址
• 深複製完全複製了一份副本，容器與容器中的元素地址都不一樣

• b = list(a)
• b = a[:]
• b = a.copy() PS: 淺複製Shallow copy
``````#%% list copy
a_list = list(a)
a_index = a[:]
a_copy = a.copy()
a.append(5)
print("Shallow copy")
print("a_list: ", a_list)
print("a_index: ", a_index)
print("a_copy: ", a_copy)
``````

``````import copy
a = [1, [2,3]]
a_deepcopy = copy.deepcopy(a)
``````

``````#%% Shallow copy and deep copy
import copy
a = [1, [2,3]]
a_ref = a
a_shallowcopy = copy.copy(a)
a_deepcopy = copy.deepcopy(a)

print("{:<15}{:<20}{}".format("a:", f"{a}", f"id:{id(a_ref)}"))
print("{:<15}{:<20}{}".format("a_shallow_copy:", f"{a_shallowcopy}", f"id:{id(a_shallowcopy)}"))
print("{:<15}{:<20}{}".format("a_deepcopy:", f"{a_deepcopy}", f"id:{id(a_deepcopy)}"))

a[0] = 4
print("\nChange immutable part: a[0] = 4")
print("{:<15}{:<20}{}".format("a:", f"{a}", f"id:{id(a_ref)}"))
print("{:<15}{:<20}{}".format("a_shallow_copy:", f"{a_shallowcopy}", f"id:{id(a_shallowcopy)}"))
print("{:<15}{:<20}{}".format("a_deepcopy:", f"{a_deepcopy}", f"id:{id(a_deepcopy)}"))
``````

``````a[1][1] = 5
print("\nChange mutable part: a[1][1] = 5")
print("{:<20}{:<20}{}".format("a:", f"{a}", f"id:{id(a_ref)}"))
print("{:<20}{:<20}{}".format("a_shallow_copy:", f"{a_shallowcopy}", f"id:{id(a_shallowcopy)}"))
print("{:<20}{:<20}{}".format("a_deepcopy:", f"{a_deepcopy}", f"id:{id(a_deepcopy)}"))

print("\nCheck variable id at deep level")
print("{:<20}{:<20}{}".format("a[1][1]:", f"{a[1][1]}", f"id:{id(a[1][1])}"))
print("{:<20}{:<20}{}".format("a_shallowcopy[1][1]:", f"{a_shallowcopy[1][1]}", f"id:{id(a_shallowcopy[1][1])}"))
print("{:<20}{:<20}{}".format("a_deepcopy[1][1]:", f"{a_deepcopy[1][1]}", f"id:{id(a_deepcopy[1][1])}"))
``````

1. 淺/深複在製第一層變數均已指向不同記憶體
BUT!!!
2. 淺複製在第二層變數仍與原始變數指向相同記憶體
3. 深複製在第二層變數已指向不同記憶體
4. 深複製 (deep copy) 建立一份完全獨立的變數

## Reference

Python中的淺複製(shallow copy)和深複製(deep copy)