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.

Get Python in a Nutshell 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.