About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Monday, September 2, 2019

Deepcopy in Python

If any list is made from existing list then changing the existing list also changes the list which is formed using reference list, to avoid this situation deepcopy function is used to form the resultant list

Problem with below code, here the list c is made from
C = [a,b], which refer to the memory of a and b to get its value and that is the reason when a or b value changes the c list value also gets change.

a = ['neha','sharma']
b=[
10,12]
print('a location:', id(a), ' b location:', id(b))
c=[a
,b]
print('c list [a,b]:', c, ' c location :', id(c))
b.insert(
2,13)
print('b after inserting 13', b)
print('b locatiton after inserting new value :', id(b))
print('c after changing b :  ',c, ' c location after change :', id(c))

Output
a location: 2639312  b location: 2640472
c list [a,b]: [['neha', 'sharma'], [10, 12]]  c location : 2996424
b after inserting 13 [10, 12, 13]
b locatiton after inserting new value : 2640472
c after changing b :   [['neha', 'sharma'], [10, 12, 13]]  c location after change : 2996424

Now, instead of creating new list with z= [x,y] , lets apply copy.deepcopy function, it will copy the content of list instead of referring to the list location , see below in the example

import copy
x=[
1,2]
y=[
4,5]
z=[copy.deepcopy(x)
,y]
print('Element of Z :', z)
print('\nLets change the value of X list, by appending')
x.append([
3,6])
print('Value of X after appending another list:', x)
print('Now lets check the value of Z :',z)

Output:
Element of Z : [[1, 2], [4, 5]]

Lets change the value of X list, by appending
Value of X after appending another list: [1, 2, [3, 6]]
Now lets check the value of Z : [[1, 2], [4, 5]]

Here if you see, the value of c list didn’t change even though we changed the value of x that is because we took deepcopy of x list while creating the z list.


Data Science with…Python J
Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment