Home >Backend Development >Python Tutorial >Python copy object
When assigning values between objects in Python, they are passed by reference. If you need to copy an object, you need to use the copy module in the standard library.
1. copy.copy shallow copy only copies the parent object, and does not copy the internal child objects of the object.
2. copy.deepcopy deep copy copies the object and its sub-objects
A good example:
import copy
a = [1, 2, 3, 4, ['a', 'b']] # Original object
b = a #Assignment, passing the reference of the object
c = copy.copy(a) #Object copy, shallow copy
d = copy. deepcopy(a) #Object copy, deep copy
##a.append( 5) #Modify object a
##a[4].append('c') #Modify the ['a', 'b'] array object in object a
print 'a = ', aprint 'b = ', b
print 'c = ', c
print 'd = ', d
Output result:
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c = [1, 2, 3, 4, ['a', 'b', 'c']]
d = [ 1, 2, 3, 4, ['a', 'b']]
The above is the detailed content of Python copy object. For more information, please follow other related articles on the PHP Chinese website!