DEV Community

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

Posted on

Shallow copy & Deep copy in Python (9)

Buy Me a Coffee

*Memo:

  • 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 a frozenset.
  • My post explains the shallow and deep 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 frozenset.
  • 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 the shallow and deep copy of a bytes.
  • My post explains the shallow and deep copy of a bytearray.
  • My post explains a string.

The same string is referred to even if copied.


A string is experimented as 2D, doing assignment and shallow and deep copy as shown below:

*Memo:

  • For a 2D string, both shallow and deep copy are impossible.
  • A string has infinite demesions(D).

<Assignment>:

*Memo:

  • v1 and v2 refer to the same shallow and deep string.
  • is keyword can check if v1 and v2 refer to the same string.

A 2D string is assigned to a variable without copied as shown below:

# Shallow string
#    ↓↓↓↓↓↓↓ 
v1 = 'abcde'
    # ↑↑↑↑↑ Deep string(Each character)
v2 = v1

print(v1, v1[2]) # abcde c
print(v2, v2[2]) # abcde c

print(v1 is v2, v1[2] is v2[2])
# True True
Enter fullscreen mode Exit fullscreen mode

<Shallow copy>:

*Memo:

  • v1 and v2 refer to the same shallow and deep string.

copy.copy() doesn't shallow-copy a 2D string as shown below:

import copy

v1 = 'abcde'
v2 = copy.copy(v1)

print(v1, v1[2]) # abcde c
print(v2, v2[2]) # abcde c

print(v1 is v2, v1[2] is v2[2])
# True True
Enter fullscreen mode Exit fullscreen mode

Slicing doesn't shallow-copy the 2D string as shown below:

v1 = 'abcde'
v2 = v1[:]

print(v1, v1[2]) # abcde c
print(v2, v2[2]) # abcde c

print(v1 is v2, v1[2] is v2[2])
# True True
Enter fullscreen mode Exit fullscreen mode

str() doesn't shallow-copy a 2D string as shown below:

v1 = 'abcde'
v2 = str(v1)

print(v1, v1[2]) # abcde c
print(v2, v2[2]) # abcde c

print(v1 is v2, v1[2] is v2[2])
# True True
Enter fullscreen mode Exit fullscreen mode

<Deep copy>:

*Memo:

  • v1 and v2 refer to the same shallow and deep string.

copy.deepcopy() doesn't deep-copy a 2D string as shown below:

import copy

v1 = 'abcde'
v2 = copy.deepcopy(v1)

print(v1, v1[2]) # abcde c
print(v2, v2[2]) # abcde c

print(v1 is v2, v1[2] is v2[2])
# True True
Enter fullscreen mode Exit fullscreen mode

Additionally, copy.deepcopy() doesn't deep-copy a string as 3D as shown below:

import copy

v1 = 'abcde'
v2 = copy.deepcopy(v1)

print(v1, v1[2], v1[2][0]) # abcde c c
print(v2, v2[2], v1[2][0]) # abcde c c

print(v1 is v2, v1[2] is v2[2], v1[2][0] is v2[2][0])
# True True True
Enter fullscreen mode Exit fullscreen mode

Top comments (0)