Shallow Copy & Deep Copy in Python (2)
Super Kai (Kazuya Ito)

Super Kai (Kazuya Ito) @hyperkai

About: I'm a web developer. Buy Me a Coffee: ko-fi.com/superkai SO: stackoverflow.com/users/3247006/super-kai-kazuya-ito X(Twitter): twitter.com/superkai_kazuya FB: facebook.com/superkai.kazuya

Joined:
Oct 21, 2021

Shallow Copy & Deep Copy in Python (2)

Publish Date: May 31
0 0

Buy Me a Coffee

*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 and v2 refer to the same shallow and deep tuple.
  • is keyword can check if v1 and v2 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Deep Copy:

deepcopy() can do deep copy:

*Memos:

  • v1 and v2 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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment