Reading Time: 1 minutes
Regular Assignment, Shallow copy & Deep Copy in Python
There are three ways to copy objects in Python: assignment, shallow copy & deep copy.
- Regular assignment points the new variable towards the original object. Let's use the builtin id() function to prove this. The id() function returns the object's memory address.
- Shallow copy
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. - Deep Copy
objOne = [1, 2, 3] objTwo = [4, 5, 6] objThree = [objOne, objTwo] objFour = objThree print( id(objThree) == id(objFour) ) # True as objThree & objFour are the same object print( id(objThree[0]) == id(objFour[0]) ) # True as objThree[0] & objFour[0] are the same object
import copy objFour = copy.copy(objThree) print( id(objThree) == id(objFour) ) # False as objFour is a new object print( id(objThree[0]) == id(objFour[0]) ) # True as objFour[0] is the same object as objThree[0]
objFour = copy.deepcopy(objThree) print( id(objThree) == id(objFour) ) # False as objFour is a new object print( id(objThree[0]) == id(objFour[0]) ) # False as objFour[0] is a new object