Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

shallow
deep
python
copies

What are shallow and deep copies?

Umme Ammara

Shallow copy

In a shallow copy, the references of an object are copied in another object when we copy the object. The referenced object itself is not copied. Any changes made to the new object will reflect in the original copy. This is shown in the example below:

food = ["apples", "burgers", "fries"]
print ("Original List", food)
#Copying the list 
food2 = food
#Change the new list 
food2[1] = "oranges"
print ("New List", food)

In the example shown above, the list food contained three different items. We copied this list into a new list, food2, modified to change the second element from burgers to oranges. This change to the new list is reflected to the original list, as seen by the output of the code above.

An illustration depicting the two lists and their references is shown below:

Deep copy

In a deep copy, a copy of the object is copied in another object. Any changes made to the new object do not reflect to the original list. This is shown in the example below:

import copy 

food = ["apples", "burgers", "fries"]
print ("Original list", food)
#create a deep copy 
food2 = copy.deepcopy(food)
#modify the new list 
food2[1] = "oranges"
print ("New list", food2)

print ("Original list", food)

In the example above, we import the copy module which lets us create a deep copy of the list food. Once the new list food2 is created, we modify this new list by changing the second element of the list from burgers to oranges. We see that this change is only reflected in the new list and the original list is the same as before.

An illustration depicting the two lists and their references is shown below:

RELATED TAGS

shallow
deep
python
copies

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring