*Memo for shallow and deep copy:
- My post explains a list.
- My post explains a tuple.
- My post explains the set with a frozenset.
- My post explains the set with a tuple.
- My post explains the set with an iterator.
- My post explains a frozenset.
- My post explains a dictionary.
- My post explains an iterator.
- My post explains a string.
- My post explains a bytes.
- My post explains a bytearray.
*Memo for others:
- My post explains a range (1).
Different ranges are referred to, only shallow-copied by slicing.
A 2D range is experimented, doing an assignment and shallow and deep copy as shown below:
*Memo:
- A 2D range can be shallow-copied (only by slicing) but cannot be deep-copied.
- A range has 2 dimensions(D).
- There are an assignment and 2 kinds of copies, shallow copy and deep copy:
- An assignment is to create the one or more references to the original top level object and (optional) original lower levels' objects, keeping the same values as before.
- A shallow copy is to create the one or more references to the new top level object and (optional) original lower levels' objects, keeping the same values as before.
- A deep copy is to create the two or more references to the new top level object and the new lower levels' objects which you desire but at least the new 2nd level objects, keeping the same values as before:
- A deep copy is the multiple recursions of a shallow copy so a deep copy can be done with multiple shallow copies.
- Basically, immutable(hashable) objects aren't copied to save memory like
str,bytes,int,float,complex,boolandtuple.
<Assignment>:
*Memo:
-
v1andv2refer to the same range and each same element. -
iskeyword can check ifv1andv2refer to the same range and each same element.
A 2D range is assigned to a variable without copied as shown below:
# Range
# ↓↓↓↓↓↓↓↓
v1 = range(5)
v2 = v1 # ↑ Each element
print(v1, *v1) # range(0, 5) 0 1 2 3 4
print(v2, *v2) # range(0, 5) 0 1 2 3 4
print(v1 is v2, v1[2] is v2[2])
# True True
<Shallow copy>:
*Memo:
-
v1andv2refer to different ranges (only by slicing) and each same element.
Slicing can shallow-copy the 2D range as shown below:
v1 = range(5)
v2 = v1[:]
print(v1, *v1) # range(0, 5) 0 1 2 3 4
print(v2, *v2) # range(0, 5) 0 1 2 3 4
print(v1 is v2, v1[2] is v2[2])
# False True
copy.copy() cannot shallow-copy a 2D range as shown below:
import copy
v1 = range(5)
v2 = copy.copy(v1)
print(v1, *v1) # range(0, 5) 0 1 2 3 4
print(v2, *v2) # range(0, 5) 0 1 2 3 4
print(v1 is v2, v1[2] is v2[2])
# True True
<Deep copy>:
*Memo:
-
v1andv2refer to the same range and each same element.
copy.deepcopy() cannot deep-copy and even shallow-copy a 2D range as shown below:
import copy
v1 = range(5)
v2 = copy.deepcopy(v1)
print(v1, *v1) # range(0, 5) 0 1 2 3 4
print(v2, *v2) # range(0, 5) 0 1 2 3 4
print(v1 is v2, v1[2] is v2[2])
# True True
Top comments (0)