Details of shallow copy and deep copy examples of Python basic tutorial
- 2020-06-12 09:49:10
- OfStack
Details of shallow copy and deep copy examples of Python foundation tutorials
There are many articles on the web about deep copy and shallow copy of Python. Here is a comparison of the three copies and attached examples for your reference
One-like replication
#encoding:utf-8
# define 1 A nested set
lista=[1,2,3,[4,5,6,[7,8,9]]]
listb=lista
# Print out lista and listb The address of the value
print id(lista) #4511103096
print id(listb) #4511103096
# Modify the lista The contents of, listb The contents of the
lista[0]=0
print lista #[0, 2, 3, [4, 5, 6, [7, 8, 9]]]
print listb #[0, 2, 3, [4, 5, 6, [7, 8, 9]]]
As you can see from the above practice, the replication operation is to point lista to the address in memory, and to point listb to it, without creating the address in memory itself.
Shallow copy
#encoding:utf-8
# define 1 A nested set
import copy
lista=[1,2,3,[4,5,6,[7,8,9]]]
# use copy In the module copy methods
listb=copy.copy(lista)
print id(lista) #4396231640
print id(listb) #4396231712
# found lista and listb The address in memory is different,
# Prints the first in the element 1 The address value of the element
print id(lista[0])#140666751466536
print id(listb[0])#140666751466536
# The address value of the element is 1 Kind of, does that mean, change lista The first of 1 An element,
# listb Or shall I change it
lista[0]=0
print lista #[0, 2, 3, [4, 5, 6, [7, 8, 9]]]
print listb #[1, 2, 3, [4, 5, 6, [7, 8, 9]]]
# Turns out, he didn't lista1 Why? Because I used a shallow copy
# Let's print it out lista[0] and listb[0] The address of the
print id(lista[0]) #140666751466560
print id(listb[0]) #140666751466536
# Will find lista[0] Redirect to another address in memory
# This can be modified by the above methods lista[3] . lista[3] Is also 1 a list
print id(lista[3])#4499779240
print id(listb[3])#4499779240
# Modify the lista[3] In the first 1 An element?
lista[3][0]=0
print lista #[0, 2, 3, [0, 5, 6, [7, 8, 9]]]
print listb #[0, 2, 3, [0, 5, 6, [7, 8, 9]]]
# Found to modify lista[3][0] The value of the element, listb[3][0] It's going to change
According to the above practice, a shallow copy does not copy objects in an object.
Deep copy
#encoding:utf-8
# define 1 A nested set
import copy
lista=[1,2,3,[4,5,6,[7,8,9]]]
# The deep copy function is an enhancement on the shallow copy, so it has the shallow copy function
listb=copy.deepcopy(lista)
lista[3][0]=0
print lista #[1, 2, 3, [0, 5, 6, [7, 8, 9]]]
print listb #[1, 2, 3, [4, 5, 6, [7, 8, 9]]]
# Deep copy will resolve the changes lista[3][0] Student: The value doesn't affect listb The values in the
# Let's modify the first one 3 Is the element in the layer list also copied
lista[3][3][0]=0
print lista #[1, 2, 3, [0, 5, 6, [0, 8, 9]]]
print listb #[1, 2, 3, [4, 5, 6, [7, 8, 9]]]
# It's not affected at all
Thank you for reading, I hope to help you, thank you for your support to this site!