Copy: Duplicate Objects

Cherima Momin
AI Perceptron
Published in
3 min readDec 21, 2020

The purpose of copy is to provide functions for duplicating objects using shallow or deep copy semantics. To make these copy work, the copy module is used.

Copy Module
The copy module includes two functions, copy() and deepcopy(), for duplicating existing objects.

  • copy.copy()
  • copy.deepcopy()

Shallow Copy

This shallow copy is created by copy(). A shallow copy constructs a new compound object and then the elements of the original object are appended to it. In a simple way, if there is any change on the copied reference, it will change the content of the main object also.

The following example illustrates how the shallow copy works.

output

Deepcopy

The deep copy created by deepcopy().To create a deep copy of a list, a new list needs to be constructed, the elements of the original list are copied and then those copies are appended to the new list. It means if there is any change in the copied reference, the main object will remain as it is.

The following example illustrates how deepcopy actually works.

output:-

customizing copy behavior

It is used to control how copies are made using the __copy__() and __deepcopy__() special methods.

  • __copy__() As we all know copy() is used for shallow copy .Here it is called without any arguments.
  • __deepcopy__() is called with a memo dictionary and return a deep copy of the object.
  • The memo dictionary is used to keep track of the values that have been copied already, so as to avoid infinite recursion.

The following example illustrates how the methods are called

output

--

--