*Memos:
- My post explains a tuple.
- My post explains the shallow and deep copy of a list.
- My post explains the shallow copy of the set with a tuple.
- My post explains the shallow and deep copy of the set with an iterator.
- My post explains the shallow and deep copy of a dictionary.
- My post explains the shallow and deep copy of an iterator.
- My post explains variable assignment.
The same tuple is always referred to because a tuple cannot be copied.
Normal Copy:
*Memos:
-
v1
andv2
refer to the same shallow and deep tuple. -
is
keyword can check ifv1
andv2
refer to the same tuple.
#### Shallow tuple ###
# ↓↓↓↓↓↓↓↓↓↓↓ ↓
v1 = ('a', 'b', ('c', 'd'))
v2 = v1 # ↑↑↑↑↑↑↑↑↑↑
# Deep tuple
print(v1) # ('a', 'b', ('c', 'd'))
print(v2) # ('a', 'b', ('c', 'd'))
print(v1 is v2, v1[2] is v2[2]) # True True
Shallow Copy:
copy() can do shallow copy as shown below. *v1
and v2
refer to the same shallow and deep tuple:
from copy import copy
v1 = ('a', 'b', ('c', 'd'))
v2 = copy(v1) # Here
print(v1) # ('a', 'b', ('c', 'd'))
print(v2) # ('a', 'b', ('c', 'd'))
print(v1 is v2, v1[2] is v2[2]) # True True
The below with tuple() which can do shallow copy is equivalent to the above:
v1 = ('a', 'b', ('c', 'd'))
v2 = tuple(v1) # Here
print(v1) # ('a', 'b', ('c', 'd'))
print(v2) # ('a', 'b', ('c', 'd'))
print(v1 is v2, v1[2] is v2[2]) # True True
The below with slice which can do shallow copy is equivalent to the above:
v1 = ('a', 'b', ('c', 'd'))
v2 = v1[:] # Here
print(v1) # ('a', 'b', ('c', 'd'))
print(v2) # ('a', 'b', ('c', 'd'))
print(v1 is v2, v1[2] is v2[2]) # True True
Deep Copy:
deepcopy() can do deep copy:
*Memos:
-
v1
andv2
refer to the same shallow and deep tuple. -
deepcopy()
should be used because it's safe, doing copy deeply.
from copy import deepcopy
v1 = ('a', 'b', ('c', 'd'))
v2 = deepcopy(v1) # Here
print(v1) # ('a', 'b', ('c', 'd'))
print(v2) # ('a', 'b', ('c', 'd'))
print(v1 is v2, v1[2] is v2[2]) # True True
Additionally, the below is a 3D tuple:
from copy import deepcopy
v1 = ('a', 'b', ('c', ('d',)))
v2 = deepcopy(v1) # Here
print(v1) # ('a', 'b', ('c', ('d',)))
print(v2) # ('a', 'b', ('c', ('d',)))
print(v1 is v2, v1[2] is v2[2], v1[2][1] is v2[2][1]) # True True True