Make Deep Copy of List in Python (Example)
In this tutorial, you’ll learn how to create a deep copy of a list in Python. A deep copy is a copy of an object that also duplicates the nested objects within it. We’ll explore different methods to make deep copies of lists.
The table of contents is structured as follows:
Let’s dive into it!
Initializing a Sample List and Importing Modules
First, let’s initialize a sample list and import the copy module that we’ll be working with throughout the tutorial:
import copy # Initializing a list original_list = [1, 2, 3, [4, 5]]
This script creates a list original_list
with elements 1, 2, 3
and [4, 5]
.
Example: Using the copy Module
We will use the copy module in Python to create a deep copy of original_list
. Here’s an example:
# Deep copy using the copy module deep_copy = copy.deepcopy(original_list) # Modify original list original_list[3][0] = 6 # Print original list print(original_list) # [1, 2, 3, [6, 5]] # Print deep copy print(deep_copy) # [1, 2, 3, [4, 5]]
In this example, we have imported the copy module and used the copy.deepcopy() function to create a deep copy of the original list. The deepcopy()
function creates a completely separate copy of the list, including any nested objects. Therefore, changes in the original list or its nested objects will not affect the deep copied object.
Video, Further Resources & Summary
In this tutorial, we explored the copy.deepcopy()
function from the copy
module allowing us to create separate copies of a list, including any nested objects.
The YouTube video will be added soon.
Furthermore, you could have a look at some of the other tutorials on Statistics Globe:
- Loop Over List with Index in Python (2 Examples)
- Define a Global List in Python
- Natural Merge Sort in Python (Example)
- How to Use Lists in Python (13 Examples)
- Find Union of Two Lists in Python (3 Examples)
Now you have the knowledge to create deep copies of lists in Python!
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter