The copy Module
As discussed in Assignment Statements, assignment in Python does not copy the righthand side object being assigned. Rather, assignment adds a reference to the righthand side object. When you want a copy of object x
, you can ask x
for a copy of itself, or you can ask x
’s type to make a new instance copied from x
. If x
is a list, list(
x
)
returns a copy of x
, as does x
[:]
. If x
is a dictionary, dict(
x
)
and x
.copy( )
return a copy of x
. If x
is a set, set(
x
)
and x
.copy( )
return a copy of x
. In each of these cases, my strong personal preference is for the uniform and readable idiom of calling the type, but there is no consensus on this style issue in the community of Python experts.
The copy
module supplies a copy
function to create and returns a copy of many types of objects. Normal copies, such as list(
x
)
for a list x
and copy.copy(
x
)
, are also known as shallow copies: when x
has references to other objects (as items or attributes), a normal (shallow) copy of x
has distinct references to the same objects. Sometimes, however, you need a deep copy, where referenced objects are copied recursively; fortunately, this requirement is rare, because a deep copy can take a lot of memory and time. Module copy
supplies a deepcopy(
x
)
function to create and return a deep copy.
copy |
Creates and returns a shallow copy of |
Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.