5.5 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.
Consider this assignment statement:
a = b
This creates two references to the same underlying object. If the value of the b variable has a mutable type, like the list, set, or dict types, then a change using either a or b will update the underlying mutable object. For more background, see the Understanding variables, references, and assignment recipe.
Most of the time, this is the behavior we want. This is ideal for providing mutable objects to functions and having a local variable in the function mutate an object created outside the function. 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...