SoFunction
Updated on 2024-10-29

Illustration of deep and shallow copy in Python (in layman's terms)

I. Shallow and deep copy

assignment operation

l1 = [1, 2, 3, [22, 33]]
l2 = l1
(666)

print(l1) # [1, 2, 3, [22, 33], 666]
print(l2) # [1, 2, 3, [22, 33], 666]

Illustration:

Attention:l2 = l1is a pointer, an assignment, and has nothing to do with shades of copy.

Shallow copy

The list is actually slots, each storing the memory address of the object.

precedent1. Adding elements to a large list
l1 = [1, 2, 3, [22, 33]]
l2 = ()
# Or the following, which is also a shallow copy
# import copy
# l2 = (l1)
(666)

print(l1) # [1, 2, 3, [22, 33], 666]
print(l2) # [1, 2, 3, [22, 33]]

precedent2. Adding elements to a small list
l1 = [1, 2, 3, [22, 33]]
l2 = ()
l1[-1].append(666)

print(l1) # [1, 2, 3, [22, 33, 666]]
print(l2) # [1, 2, 3, [22, 33, 666]]、

precedent3. commander-in-chief (military)l1The first element of the list is changed to6
l1 = [1, 2, 3, [22, 33]]
l2 = ()
l1[0] = 6

print(l1) # [6, 2, 3, [22, 33]]
print(l2) # [1, 2, 3, [22, 33]]

Illustration:

Example 1

Example 2

Example 3

Summary:

Shallow copy: A new space is created in memory to hold the copied list, but the contents of the list still follows the memory address of the previous object.

Attention:

In slicing, if it is a full cut, it is a shallow copy.

Deep copy

import copy
l1 = [1, 2, 3, [22, 33]]
l2 = (l1)
(666)
print(l1) # [1, 2, 3, [22, 33], 666]
print(l2) # [1, 2, 3, [22, 33]]

Illustration:

The essence is shown below:

But python has an optimization for deep copy that recreates a copy of the mutable datatypes in memory, while the immutable datatypes follow the previous one, so it looks like the following in memory:

Summary:

Deep copy: it opens a new space in memory and creates a new copy of the original list and the mutable datatypes inside the list, while the immutable datatypes are kept as they were before.

To this point this article on the illustration of Python shallow copy (easy to understand) of the article is introduced to this, more related to Python shallow copy content, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!