The copy Module
As discussed in Chapter 4, assignment in Python does not copy the
right-hand side object being assigned. Rather, assignment adds a
reference to the right-hand side object. When you want a copy of
object x, you can ask
x for a copy of itself. If
x is a list,
x
[:] is a copy of
x. If x is a
dictionary, x
.copy( )
returns a copy of x.
The copy module supplies a copy
function that creates and returns a copy of most types of objects.
Normal copies, such as
x
[:] for a list
x and
copy.copy(
x
),
are also known as shallow copies. When x
has references to other objects (e.g., items or attributes), a normal
copy of x has distinct references to the
same objects. Sometimes, however, you need a deep copy, where
referenced objects are copied recursively. Module
copy supplies a
deepcopy(
x
)
function that performs a deep copy and returns it as the
function’s result.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access