*Memos:
- My post explains a set and copy.
- My post explains the shallow and deep copy of a list.
- My post explains the shallow and deep copy of 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.
<A set with a tuple>
A set can have a tuple and iterator but cannot have a set, list and dictionary. *The same tuple is always referred to because a tuple cannot be copied according to the experiments so for the set with a tuple, only shallow copy is possible.
Normal Copy:
*Memos:
-
A
andB
refer to the same shallow set and deep tuple. -
is
keyword can check ifv1
andv2
refer to the same set or tuple.
# Shallow set # ↓ ↓ A = {('a',)} # ↑↑↑↑↑↑ Deep tuple B = A print(A) # {('a',)} print(B) # {('a',)} print(A is B) # True print(A.pop()) # ('a',) print(B.pop()) # KeyError: 'pop from an empty set'
Shallow Copy:
copy() can do shallow copy as shown below:
*Memos:
-
A
andB
refer to different shallow sets. -
A
andB
refer to the same deep tuple.
A = {('a',)} B = A.copy() # Here print(A) # {('a',)} print(B) # {('a',)} print(A is B) # False v1 = A.pop() v2 = B.pop() print(v1) # ('a',) print(v2) # ('a',) print(v1 is v2) # True
The below with copy() which can do shallow copy is equivalent to the above:
from copy import copy A = {('a',)} B = copy(A) # Here print(A) # {('a',)} print(B) # {('a',)} print(A is B) # False v1 = A.pop() v2 = B.pop() print(v1) # ('a',) print(v2) # ('a',) print(v1 is v2) # True
The below with deepcopy() which can do deep copy is equivalent to the above. *deepcopy()
should be used because it's safe, doing copy deeply:
from copy import deepcopy A = {('a',)} B = deepcopy(A) # Here print(A) # {('a',)} print(B) # {('a',)} print(A is B) # False v1 = A.pop() v2 = B.pop() print(v1) # ('a',) print(v2) # ('a',) print(v1 is v2) # True
The below with set() which can do shallow copy is equivalent to the above:
A = {('a',)} B = set(A) # Here print(A) # {('a',)} print(B) # {('a',)} print(A is B) # False v1 = A.pop() v2 = B.pop() print(v1) # ('a',) print(v2) # ('a',) print(v1 is v2) # True
Additionally, the below is the 3D set with a 2D tuple:
from copy import deepcopy A = {(('a',),)} B = deepcopy(A) # Here print(A) # {(('a',),)} print(B) # {(('a',),)} print(A is B) # False v1 = A.pop() v2 = B.pop() print(v1) # (('a',),) print(v2) # (('a',),) print(v1[0]) # ('a',) print(v2[0]) # ('a',) print(v1 is v2, v1[0] is v2[0]) # True True
Top comments (0)