DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Shallow Copy & Deep Copy in Python (2)

Buy Me a Coffee

*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 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.copy() does shallow copy as shown below:

*Memo:

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

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

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

<Deep Copy>:

copy.deepcopy() does deep copy as shown below:

*Memo:

  • v1 and v2 refer to the same shallow and deep tuple.
  • copy.deepcopy() should be used because it's safe, doing copy deeply while copy.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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)