Show the difference between a shallow copy and a deep copy of a nested Python structure.
A shallow copy makes a new outer container but keeps the objects that are inside it. A deep copy makes new copies of everything, all the way down.
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]] - the inner list is shared
print(shallow is original) # False - the outer list is new
deep[0].append(77)
print(original) # [[1, 2, 99], [3, 4]] - unchanged
print(deep) # [[1, 2, 77], [3, 4]]
The shallow copy printed a modified original, and that is exactly the point. The new outer list has its own slots, but slot zero still points at the same inner list, so adding an item through the copy is visible through the original as well.
The deep copy made the same change and the original did not move, because deepcopy walked through the whole structure and built new inner lists as well. The last two lines show that the original still holds the 99 from the shallow experiment, while the deep copy holds its own 77.
There are three other ways to make a shallow copy that come up often. The slicing habit items[:] and the constructor list(items) both give you a new list with the same elements inside it. The built-in methods dict.copy, set.copy, and list.copy do the same thing for their own types. All of them are shallow.
Deep copying has a cost that is worth mentioning. It walks through the entire object graph, so it is slow for large structures. It can also fail on objects that cannot be copied, such as an open file handle or a database connection. That is why deep copying an object that holds a connection is a common bug, because the copy ends up holding a reference to a connection that it does not own.