And since data structures contain references to objects and not the objects themselves, what happens when you make a copy of the data structure? Let’s find out.
This text is part of a Real Python tutorial by Dan Bader.
Assignment statements in Python do not create copies of objects, they only bind names to an object. For immutable objects, that usually doesn’t make a difference.
But for working with mutable objects or collections of mutable objects, you might be looking for a way to create “real copies” or “clones” of these objects.
Essentially, you’ll sometimes want copies that you can modify without automatically modifying the original at the same time. In this article I’m going to give you the rundown on how to copy or “clone” objects in Python 3 and some of the caveats involved.
Note: This tutorial was written with Python 3 in mind but there is little difference between Python 2 and 3 when it comes to copying objects. When there are differences I will point them out in the text.
Let’s start by looking at how to copy Python’s built-in collections. Python’s built-in mutable collections like lists, dicts, and sets can be copied by calling their factory functions on an existing collection:
new_list = list(original_list)
new_dict = dict(original_dict)
new_set = set(original_set)
However, this method won’t work for custom objects and, on top of that, it only creates shallow copies. For compound objects like lists, dicts, and sets, there’s an important difference between shallow and deep copying:
-
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won’t create copies of the child objects themselves.
-
A deep copy makes the copying process recursive. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. Copying an object this way walks the whole object tree to create a fully independent clone of the original object and all of its children.
I know, that was a bit of a mouthful. So let’s look at some examples to drive home this difference between deep and shallow copies.
Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
Making Shallow Copies
In the example below, we’ll create a new nested list and then shallowly copy it with the list()
factory function:
>>> xs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> ys = list(xs) # Make a shallow copy
This means ys
will now be a new and independent object with the same contents as xs
. You can verify this by inspecting both objects: