How to Deep Copy a List in Python

In this post, we will see how to deep copy a list in Python.

Python mainly supports two different ways to copy the contents of one variable to another. Both these methods namely shallow copy and deep copy are extensively used in Python depending on the programmer’s needs. This tutorial demonstrates how to deep copy a list in Python. The methods mentioned in this article are restricted to just lists and are not applicable in the case of other sequence or mapping data types in Python.

Before we move on, let us understand what the basic terminologies involved in this article are.

What is a list in Python?

We make use of lists when there is a need to stock several items in a single variable. Lists can be defined with the help of square brackets [] and are one among the 4 data types that Python provides to store stocks of data in a single variable. The items confined under a list are always changeable and ordered. Lists also allow duplicity in data.

What are shallow copy and deep copy operations in Python?

Before explaining these terms, we should note that the below explanation only holds true in cases of compound objects, or simply the objects that hold several objects in it).

Shallow Copy

A shallow copy of a list creates a new copy list and inserts the references of the original list into this newly created list. This means that any change in one of these two lists would simply lead to a change in the other as well as the objects of both these lists having the same address.

Deep Copy

A deep copy of a list creates a new copy list and then proceeds to insert into it, the copies of the objects inside the original list. This means that any change in one of these two main lists would not lead to a change in the other as each of the lists now has its own separate identity and have no references between them.

How to deep copy a list in Python?

Using the deepcopy() function from the copy module to deep copy a list in Python.

The deepcopy() function from the copy module can be utilized to make a deep copy of a list in Python. It is the most common way of making a deep copy of a list.

The copy module in Python provides both shallow and deep copy operations for data types that store a mutable collection in Python.

The following code uses the deepcopy() function from the copy module to deep copy a list in Python.

The above code provides the following output:

[[1, 8], [7, ‘Hunted’]] [[1, 5], [7, ‘Hunter’]]

Here, we should note that when the original list is tampered with, it does not have any impact on the new copy list created in the code.

Using a user-defined function to deep copy a list in Python.

Instead of utilizing any excess modules, we can simply create a function that can achieve the task of carrying out a deep copy operation on a given list. As mentioned previously, this user defined function need not have any libraries imported to the python code in order to function properly.

The following code uses a user-defined function to deep copy a list in Python.

The above code provides the following output:

[[1, 8], [7, ‘Hunted’]] [[1, 5], [7, ‘Hunter’]]

The code mentioned in the above box creates a user-defined function with the help of the if...else iteration statement. The custom dcopy() function now created by the programmer functions similar to the copy.deepcopy() function from the copy module.

Using list comprehension to deep copy a list in Python.

List comprehension is one way to efficiently create a list with the help of an already existing list. Moreover, list comprehension compresses the process of writing the code to create a new list by reducing it to a single line. It is an easy-to-understand method that decreases the complexity of list definition.

The following code uses list comprehension to deep copy a list in Python.

The above code provides the following output:

[1, 4, 7] [1, 5, 7]

We have taken a simple example of a list, but like the methods mentioned above, we can simply take nest the list comprehension when dealing with an original list of lists. Moreover, this method works only in the cases when primitive data types are taken as elements of the list, which are mainly Strings, Integers, Floating-point numbers, and Boolean values.

Conclusion

The article was focused on and provided the different ways available to deep copy a list in Python. The deepcopy() method can be utilized after importing its parent module copy into the code while a user-defined function can also be created in place of it if there is a restriction on importing modules to the code. The third method, list comprehension works well when dealing with any of the four primitive data types as the elements contained within the list.

That’s all about how to deep copy a List in Python

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 27 November

    Remove Punctuation from List in Python

    Table of ContentsUse for loop with replace() MethodUse Nested List ComprehensionUse str.translate() Function Use for loop with replace() Method To remove punctuation from list in Python: Use the for loop to iterate over each word (element) of given list. Use a nested loop to iterate over each character in the word. Use the if statement […]

  • 04 October

    Get Every Other Element in List in Python

    Table of ContentsGet Every Other Element in List in PythonUsing List SlicingUsing the list.append() function along with the range() functionUsing list comprehension and the range() function with conditionalsUsing list comprehension and the range() function with stepUsing the enumerate() function along with list comprehensionUsing a lambda functionConclusion. A list is one of the more versatile data […]

  • 23 September

    Add Tuple to List in Python

    Table of ContentsAdd tuple to list in PythonWays to Add Tuple to List in Python (adding the Tuple as An Element)Using the insert() Function to Add Tuple to List in PythonUsing the append() Function to Add Tuple to List in PythonWays to Add Tuple to List in Python (adding the Tuple’s Elements to A List)Using […]

  • 24 May

    Replace Comma with Space in List in Python

    Table of ContentsHow to replace comma with space in list in PythonUsing the replace() function to replace comma with space in list in PythonUsing the re.sub() function to replace comma with space in list in PythonUsing the split() and join() functions to replace comma with space in list in Python.Conclusion In this post, we will […]

  • 19 May

    Compare list elements with each other in Python

    Table of ContentsCompare all elements in list PythonWays to compare list elements with each other in PythonUsing the for loop to compare all elements in list PythonUsing the itertools.combinations() function to compare all elements in list PythonConclusion In this post, we will see how to compare list elements with each other in Python. Compare all […]

  • 18 May

    Convert Generator to List in Python

    Table of ContentsLists and Generators in PythonWays to convert generator to list in PythonUsing the list() function to convert generator to list in PythonUsing the unpack operator * to convert generator to list in PythonUsing the list comprehension to convert generator to list in PythonUsing the append() function to convert generator to list in PythonConclusion […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.