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 b
is a list, both a
and b
are references to the same, mutable list.
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