0% found this document useful (0 votes)
5 views2 pages

Shallow and Deep

The document explains the use of Python's copy module for shallow and deep copy operations. A shallow copy creates a new object that references the original elements without copying nested objects, while a deep copy creates a new object and recursively copies all nested objects. Examples demonstrate the differences in behavior when modifying the original list after creating shallow and deep copies.

Uploaded by

madhan95ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Shallow and Deep

The document explains the use of Python's copy module for shallow and deep copy operations. A shallow copy creates a new object that references the original elements without copying nested objects, while a deep copy creates a new object and recursively copies all nested objects. Examples demonstrate the differences in behavior when modifying the original list after creating shallow and deep copies.

Uploaded by

madhan95ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

We use the copy module of Python for shallow and deep copy

operations.
import copy
copy.copy(k)
copy.deepcopy(k)
k represents the original list.
Shallow Copy
A shallow copy creates a new object which stores the reference of
the original elements.
So, a shallow copy doesn't create a copy of nested objects, instead it
just copies the reference of nested objects. This means, a copy
process does not recurse or create copies of nested objects itself.
Adding new nested object using Shallow copy
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'A'
print("Old list:", old_list)
print("New list:", new_list)

output:
Old list: [[1, 1, 1], [2, 'A', 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 'A', 2], [3, 3, 3]]
Deep Copy
A deep copy creates a new object and recursively adds the copies of
nested objects present in the original elements. The deep copy
creates independent copy of original object and all its nested objects.
Adding a new nested object in the list using Deep copy
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'B'
print("Old list:", old_list)
print("New list:", new_list)
output:
Old list: [[1, 1, 1], ['B', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

You might also like