Home » Python

Shallow Copy Vs Deep Copy in Python

Python Shallow vs Deep Copy: Here, we are going to learn what are the shallow copy and deep copy in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on October 03, 2019

In python, the assignment operator does not copy the objects, instead, they create bindings between an object and the target. The object, if a collection that is mutable or consists of mutable items uses the copy so that one can change one copy without changing the other.

The module copy provides generic shallow and deep copy operations,

Shallow Copy

A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original. This process is not recursive and hence doesn't create copies of the child object. In shallow copy, a reference of object is copied to another object, meaning any changes made to the copy of the object shall reflect on the original object too.

    copy.copy(x)  # returns shallow copy

Example:

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> xs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> ys = copy.copy(xs)
>>> print(xs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(ys)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> xs.append(['new sublist']) # Modifying the copied list at a "superficial" level was no problem at all.
>>> print(xs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], ['test']]
>>> print(ys)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> xs[1][0] = 'X1' // changes both 'xs' and 'ys'
>>> print(xs)
[[1, 2, 3], ['X1', 5, 6], [7, 8, 9], ['test']]
>>> print(ys)
[[1, 2, 3], ['X1', 5, 6], [7, 8, 9]]

Deep Copy

A deep copy constructs a new compound object and then recursively inserts the copies into it the objects found in the original.

    copy.deepcopy(x) # returns a deep copy

Example:

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import copy
>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zs = copy.deepcopy(ys)
>>> ys[1][1] = 'X'
>>> print(ys)
[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
>>> print(zs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>

Important reminders

  • Shallow copying of an object will not clone the child objects. Hence, the child copy is not fully independent of the parent.
  • A deep copy of an object will recursively clone the child object and hence the child object is fully independent of the parent. Creating a deep copy is slower.
  • An arbitrary object, including custom classes, can be copied using the copy module.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.