The examples in this article describe Python shallow copy and deep copy usage. Share to everyone for your reference. The specific analysis is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12-13 |
>>> person=[' name ', [' savings ', MB]] >>> hubby=person[:] >>> wifey=list (person) >> > [ID (x) for x in Person,hubby,wifey] [3074051788L, 3074061740L, 3074061996L] >>> [ID (y) for x in Person,hubby , Wifey for y in x] [3074319552l,3073979916l,3074319552l,3073979916l,3074319552l,3073979916l] >>> hubby[0]= ' Joe ' >>> wifey[0]= ' Jane ' ([' Joe ', [' savings ', 100]],[' Jane ', [' savings ', 100]],[' name ', [' savings ', MB]]) > >> hubby[1][1]=70 >>> Hubby,wifey,person ([' Joe ', [' savings ', 70]],[' Jane ', [' savings ', 70]],[' name ',] [' Savings ', 70]] |
A shallow copy creates a new object, but its object reference is identical to the object being copied.
If the constituent elements of the copied object are immutable types, the change of the copied object to this element is actually creating a new object.
If the constituent element of the copied object is a mutable type, then the change of the copied object to the element is actually modifying the contents of the memory space on the original object's memory space.
In this way, only hubby[1][1]=70 can result in the change of Wifey,person corresponding value.
I hope this article will help you with your Python programming.