Header Ads

Header ADS

Python Copy Module


Python Copy Module

python copy module is used for copying elements of a list, object, array etc.

Python copy module is used to creating shallow as well as deep copies.

copy module is a built-in package for python 3.x version.

The copy module basically have two functions
  1. copy( )
  2. deepcopy( )

we will discuss each one by one but first understand the usage of copy module.

Lets take a example code and copy a list with out copy module functions.

       			 
#Dynamic Coding
#copy module
# working without copy module.

a = [[1, 2, 3],[4,5,6]]
b = a


print(a)
print(b)

a[1][1] = 23
b[0][0] = 98


print('List a ',a)
print()
print('List a ',b)
 

  Output  

[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

List a [[98, 2, 3], [4, 23, 6]]

List a [[98, 2, 3], [4, 23, 6]]

This code represents an example of shallow copy.

As you can see in the output the change on list  a at index 1 is also reflected on on list b and same the change on list b index 0 is visible on list a & because of this we use copy module function method because when we modify one list the another list which is the copy of first list will not affected if we are using deepcopy( ) method of copy module.

Lest move to our topic .

1. copy.copy( )  :

This method creates shallow copy of a list or array etc.
shallow copy means both list will point to same object.

code to illustrate:
       			 
#Dynamic Coding
#copy module

import copy

a = [[1, 2, 3],[4,5,6]]

b = copy.copy(a)

print(a)
print(b)

a[1][1] = 23
b[0][0] = 98


print('List a ',a)
print()
print('List a ',b)
 

  Output  

[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

List a [[98, 2, 3], [4, 23, 6]]

List a [[98, 2, 3], [4, 23, 6]]


Note : in our code we use a 2 dimensional list but if we use a 1 D list then the copy( ) function will work same like deepcopy( ) function means the modification of one will not affect other.


2. copy.deepcopy( )  :

The deepcopy( ) method returns a deepcopy of the list passed to it.

The deepcopy( ) creates a separate list with no relation with original one.
it basically means the change on list 1 will not affect list 2 which is the copy of list 1 and viceversa.

in deepcopy both list will point on different object.

code to illustrate:

       			 
#Dynamic Coding 
# copy module
# deep copy 
import copy

a = [1, 2, 3]


b = copy.deepcopy(a)

print(a)
print(b)

a[1] = 23
b[0]= 98

print('List a ',a)
print()
print('List a ',b)
 

  Output  

[1, 2, 3]
[1, 2, 3]

List a [1, 23, 3]

List a [98, 2, 3]

As you can see in the output we change data at both list index but modification of one list is not reflected to Another list.






Thanks for Visiting.
if you face any error or doubt let us know in comment section,. we will reply back you as soon as possible.


No comments

Powered by Blogger.