*Memo:
- 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 a tuple.
The same tuple is always referred to because a tuple cannot be copied.
<Normal Copy>:
*Memo:
-
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.copy() does shallow copy as shown below:
*Memo:
-
v1
andv2
refer to the same shallow and deep tuple.
import copy
v1 = ('a', 'b', ('c', 'd'))
v2 = copy.copy(v1)
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 slicing which does shallow copy is equivalent to the above:
v1 = ('a', 'b', ('c', 'd'))
v2 = v1[:]
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 doesn't shallow copy is equivalent to the above:
*Memo:
- Again,
tuple()
doesn't do shallow copy.
v1 = ('a', 'b', ('c', 'd'))
v2 = tuple(v1)
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>:
copy.deepcopy() does deep copy as shown below:
*Memo:
-
v1
andv2
refer to the same shallow and deep tuple. -
copy.deepcopy()
should be used because it's safe, doing copy deeply whilecopy.copy()
,tuple()
and slicing aren't safe, doing copy shallowly.
import copy
v1 = ('a', 'b', ('c', 'd'))
v2 = copy.deepcopy(v1)
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:
import copy
v1 = ('a', 'b', ('c', ('d',)))
v2 = copy.deepcopy(v1)
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
Top comments (0)