Making shallow and deep copies of objects
Throughout this chapter, we've talked about how assignment statements share references to objects. Objects are not normally copied. When we write:
a = b
we now have two references to the same underlying object. If the object of b
has a mutable type, like the list
, set
, or dict
types, then both a
and b
are references to the same mutable object.
As we saw in the Understanding variables, references, and assignment recipe, a change to the a
variable changes the list object that both a
and b
refer to.
Most of the time, this is the behavior we want. There are rare situations in which we want to actually have two independent objects created from one original object.
There are two ways to break the connection that exists when two variables are references to the same underlying object:
- Making a shallow copy of the structure
- Making a deep copy of the structure
Getting ready
Python does...