Shallow Copy vs Deep Copy
Explore how shallow and deep copies work in Python for built-in and custom objects. Understand when to use each copying method to maintain object independence and avoid unintended modifications. This lesson clarifies the concepts using practical examples involving lists and custom classes.
We'll cover the following...
We'll cover the following...
In this section, we’ll learn how to copy the objects in Python. You must have heard the terms shallow copy and deep copy before.
Alert: Just a heads up that for primitive types (int), there’s no difference between a shallow copy and a deep copy.
Python’s built-in mutable objects can be copied by using their constructor. For example:
l2 = list(l1) # List l1 copied with list()
d2 = dict(d1) # Dictionary d2 copied with dict()
s2 = set(s1) # Set s2 copied with set()
Shallow copy
Creating an object and populating it with the references to the ...