What Are Shallow and Deep Copies?

Sometimes we need to create copies of objects. At first glance, this might not seem particularly exciting. However, when it comes to compound objects, a few important questions arise. We consider an object to be compound if it contains other objects—in other words, if it holds references to them. In this case, the key question is whether copying affects only the container object, or its components as well.

The term „shallow copy” is used when only the container object itself becomes a new object, while the component objects are not duplicated—only their references are copied. However, if both the container object and all of its components have distinct identities in the copy, then this is called a „deep copy.”

In Python’s standard library, the copy module provides tools for both approaches. The copy() function creates a shallow copy of the given object, while deepcopy() performs a deep copy.

Below, you can see a visual illustration of the conceptual difference between shallow and deep copying.

In the following code example, you can observe the difference between these two approaches. We copy two compound objects: a mutable container (in this case, a list) and an instance of a simple user-defined class.

First, we create both shallow and deep copies, and print them. Then, for the list, we modify the contents of the first element of the original object; for the class instance, we change the value of one of its attributes. Then, we print the state after these modifications. As you can see, in both cases, the changes are reflected in the shallow copies, but not in the deep copies, because the latter are completely independent of the original objects.

For a more detailed discussion of this topic, see the chapter “Copying Compound Objects” in the e-book Python Knowledge Building Step by Step from the Basics to the First Desktop Application, which also explains how to customize copying behavior for user-defined classes—this is useful when you don’t want every attribute to be duplicated during a copy() or deepcopy() operation.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?