Python Learning Notes: Deep Understanding of Shallow and Deep Copy

Hello everyone! Today I bring you the twenty-second learning note, to discuss a common pitfall in Python—shallow and deep copy. This is a concept that many beginners easily confuse, and understanding them can help avoid many strange bugs~

1. Let’s look at a practical scenario

Suppose we have a list of students:

students = ["Xiao Ming", ["Xiao Hong", "Xiao Gang"], "Xiao Li"]

Now we need to copy the list for modification, how would you do it? What happens if you just assign it directly?

new_students = students  # Is this really a copy? ==> This is not a copy, just creating a new reference
new_students[0] = "Zhang San"
print(students) # What will it output?

Problem: The original list has also been modified! This is not the independent copy we wanted.

2. Shallow Copy (Shallow Copy): Only copies the top layer

1. What is shallow copy

Shallow copy creates a new object but only copies the outermost elements

2. Implementation methods

import copy
# Method 1: Slicing operation
new_list1 = students[:]
# Method 2: list.copy() method (Python 3.3+)
new_list2 = students.copy()
# Method 3: copy module
new_list3 = copy.copy(students)

3. Characteristics and limitations

# Outer elements can be modified independently

new_list1[0] = "Li Si"
# The original list is not affected
# Modifying inner nested objects (shared reference)
new_list1[1][0] = "Wang Wu"
print(students) # Output: ['Xiao Ming', ['Wang Wu', 'Xiao Gang'], 'Xiao Li']

Key points:

  • Creates a new outer container object

  • Inner elements are still references to the original objects

  • Suitable for single-layer data structures

3. Deep Copy (Deep Copy): Completely copies

1. What is deep copy

Recursively copies all levels of objects

2. Implementation methods

import copy
deep_copy = copy.deepcopy(students)

3. Core features

# Modifying any level does not affect the original object
deep_copy[1][0] = "Zhao Liu"
print(students) # Remains unchanged: ['Xiao Ming', ['Wang Wu', 'Xiao Gang'], 'Xiao Li']

Note:

  • Recursively copies all level objects

  • Creates a completely independent copy

  • Consumes more memory and time

4. Comparison Summary

Feature Direct Assignment Shallow Copy Deep Copy
Outer Layer Independence
Inner Layer Independence
Memory Usage Least Medium Most
Time Complexity O(1) O(n) O(n)
Applicable Scenarios Reference Passing Single Layer Structure Complex Nested Structure

5. Usage Scenario Recommendations

1. Use shallow copy:

  • Simple data structures (single-layer lists/dictionaries)

  • Performance-sensitive scenarios

  • When inner layer independence is not needed

2. Use deep copy:

  • Multi-layer nested structures

  • When a completely independent copy is needed

  • Scenarios requiring isolation of configuration information

6. Special Considerations

1. Copying custom objects:

  • Shallow copy defaults to only copying the outermost object

  • Deep copy requires the object to support the pickle protocol

2. Circular reference issues:

a = []; a.append(a)
# copy.deepcopy(a)  # Can correctly handle circular references

3. Consider alternative solutions:

  • No need to copy for immutable data

  • Consider using immutable types (like tuple) to avoid accidental modifications

7. Small Exercises

  1. Create a nested list and try modifying it with shallow copy

  2. Modify the same list using deep copy

  3. Compare the changes in the original list under both methods

(Feel free to share your findings in the comments~)

Next time we will continue exploring Python, making a little progress every day, let’s work hard together on the learning journey! If you have any questions, feel free to leave a comment for discussion~

Leave a Comment