Python: Shallow copy vs deepcopy

Normal assignment simply points the new variable towards the existing object.

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.
To demonstrate, see the following example:

import copy

x = [1, 2, 3]
y = [4, 5, 6]
z = [x, y]
 
Normal assignment example:
w = z

print id(z) == id(w)          # True - w is the same object as z
print id(z[0]) == id(w[0])    # True - w[0] is the same object as z[0]
 
Shallow copy example:
w = copy.copy(z)

print id(z) == id(w)          # False - w is now a new object
print id(z[0]) == id(w[0])    # True - w[0] is still the same object as z[0]
 
Deep copy example:
w = copy.deepcopy(z)

print id(z) == id(w)          # False - w is now a new object
print id(z[0]) == id(w[0])    # False - w[0] is also a new object
 

About

Search

PISIKA Copyright © 2009