A Brief Look at Copying in Python
Contents
Here are three different lists to demonstrate the differences between various copy methods:
import copy
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]- Using normal assignment operations to copy:
d = c
print (id(c) == id(d)) # True - d and c are the same object
print (id(c[0]) == id(d[0])) # True - d[0] and c[0] are the same object- Using a shallow copy:
d = copy.copy(c)
print (id(c) == id(d)) # False - d is a new object, different from c
print (id(c[0]) == id(d[0])) # True - d[0] and c[0] are still the same object- Using a deep copy:
d = copy.deepcopy(c)
print (id(c) == id(d)) # False - d is a new object, different from c
print (id(c[0]) == id(d[0])) # False - d[0] is a new object, different from c[0]