*My post explains variable assignment in Python.
Normal Copy:
*Memos:
- The reference of a list is stored in a variable.
v1andv2have the same references of the same shallow list.
v1andv2have the same references of the same deep list.
#### Shallow list ####
# ↓↓↓↓↓↓↓↓↓↓↓ ↓
v1 = ['a', 'b', ['c', 'd']] # Equivalent
v2 = v1 # ↑↑↑↑↑↑↑↑↑↑ # v1 = v2 = ['a', 'b', ['c', 'd']]
# Deep list
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'b', ['c', 'd']]
v2[1] = 'B'
v2[2][0] = 'C'
# ↓↓↓ ↓↓↓ ↓↓↓ ↓↓↓
print(v1, v2) # ['a', 'B', ['C', 'd']] ['a', 'B', ['C', 'd']]
Shallow Copy
*Memos:
copy() can be used for shallow copy.
v1andv2have the different references of the different shallow lists.
v1andv2have the same references of the same deep list.
v1 = ['a', 'b', ['c', 'd']]
v2 = v1.copy()
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'b', ['c', 'd']]
v2[1] = 'B'
v2[2][0] = 'C'
# ↓↓↓ ↓↓↓ ↓↓↓
print(v1, v2) # ['a', 'b', ['C', 'd']] ['a', 'B', ['C', 'd']]
*The below with copy() is equivalent to the above.
import copy
v1 = ['a', 'b', ['c', 'd']]
v2 = copy.copy(v1)
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'b', ['c', 'd']]
v2[1] = 'B'
v2[2][0] = 'C'
# ↓↓↓ ↓↓↓ ↓↓↓
print(v1, v2) # ['a', 'b', ['C', 'd']] ['a', 'B', ['C', 'd']]
*The below with list() is equivalent to the above.
v1 = ['a', 'b', ['c', 'd']]
v2 = list(v1)
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'b', ['c', 'd']]
v2[1] = 'B'
v2[2][0] = 'C'
# ↓↓↓ ↓↓↓ ↓↓↓
print(v1, v2) # ['a', 'b', ['C', 'd']] ['a', 'B', ['C', 'd']]
Deep Copy
*Memos:
deepcopy() can be used for deep copy.
v1andv2have the different references of the different shallow lists.
v1andv2have the different references of the different deep lists.
import copy
v1 = ['a', 'b', ['c', 'd']]
v2 = copy.deepcopy(v1)
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'b', ['c', 'd']]
v2[1] = 'B'
v2[2][0] = 'C'
# ↓↓↓ ↓↓↓
print(v1, v2) # ['a', 'b', ['c', 'd']] ['a', 'B', ['C', 'd']]