The Wayback Machine - https://web.archive.org/web/20240921214045/https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/
Open In App

copy in Python (Deep Copy and Shallow Copy)

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create “real copies” or “clones” of these objects, we can use the copy module in Python.

Syntax of Python Deepcopy

Syntax: copy.deepcopy(x)

Syntax of Python Shallowcopy

Syntax: copy.copy(x)

Example:

In order to make these copies, we use the copy module. The copy() returns a shallow copy of the list, and deepcopy() returns a deep copy of the list. As you can see that both have the same value but have different IDs.

Example: This code showcases the usage of the copy module to create both shallow and deep copies of a nested list li1. A shallow copy, li2, is created using copy.copy(), preserving the top-level structure but sharing references to the inner lists. A deep copy, li3, is created using copy.deepcopy(), resulting in a completely independent copy of li1, including all nested elements. The code prints the IDs and values of li2 and li3, highlighting the distinction between shallow and deep copies in terms of reference and independence.

Python
import copy
li1 = [1, 2, [3, 5], 4]
li2 = copy.copy(li1)
print("li2 ID: ", id(li2), "Value: ", li2)
li3 = copy.deepcopy(li1)
print("li3 ID: ", id(li3), "Value: ", li3)

Output:

li2 ID:  2521878674624 Value:  [1, 2, [3, 5], 4]
li3 ID: 2521878676160 Value: [1, 2, [3, 5], 4]

What is Deep copy in Python?

A deep copy creates a new compound object before inserting copies of the items found in the original into it in a recursive manner. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. 

Deep copy in Python

Example:

In the above example, the change made in the list did not affect other lists, indicating the list is deeply copied.  

This code illustrates deep copying of a list with nested elements using the copy module. It initially prints the original elements of li1, then deep copies them to create li2. A modification to an element in li2 does not affect li1, as demonstrated by the separate printouts. This highlights how deep copying creates an independent copy, preserving the original list’s contents even after changes to the copy.

Python
import copy
li1 = [1, 2, [3,5], 4]
li2 = copy.deepcopy(li1)
print ("The original elements before deep copying")
for i in range(0,len(li1)):
    print (li1[i],end=" ")

print("\r")
li2[2][0] = 7
print ("The new list of elements after deep copying ")
for i in range(0,len( li1)):
    print (li2[i],end=" ")

print("\r")
print ("The original elements after deep copying")
for i in range(0,len( li1)):
    print (li1[i],end=" ")

Output:

The original elements before deep copying
1 2 [3, 5] 4
The new list of elements after deep copying
1 2 [7, 5] 4
The original elements after deep copying
1 2 [3, 5] 4

What is Shallow copy in Python?

A shallow copy creates a new compound object and then references the objects contained in the original within it, which means it constructs a new collection object and then populates it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of an object is copied into another object. It means that any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “copy()” function. 

Shallow copy in Python

Example:

In this example, the change made in the list did affect another list, indicating the list is shallowly copied. Important Points: The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Example: This code demonstrates shallow copying of a list with nested elements using the ‘copy' module. Initially, it prints the original elements of li1, then performs shallow copying into li2. Modifying an element in li2 affects the corresponding element in li1, as both lists share references to the inner lists. This illustrates that shallow copying creates a new list, but it doesn’t provide complete independence for nested elements.

Python
import copy
li1 = [1, 2, [3,5], 4]
li2 = copy.copy(li1)
print ("The original elements before shallow copying")
for i in range(0,len(li1)):
    print (li1[i],end=" ")

print("\r")
li2[2][0] = 7
print ("The original elements after shallow copying")
for i in range(0,len( li1)):
    print (li1[i],end=" ")

Output:

The original elements before shallow copying
1 2 [3, 5] 4
The original elements after shallow copying
1 2 [7, 5] 4

RECOMMENDED ARTICLES – Difference between Shallow and Deep copy of a class

copy in Python (Deep Copy and Shallow Copy) – FAQs

What is the difference between deep copy and shallow copy in Python?

The main difference between deep copy and shallow copy in Python is how they handle the objects they copy:

  • Shallow Copy: Creates a new object, but inserts references into it to the objects found in the original. It copies the top-level structure of the object, but not the nested objects within.
  • Deep Copy: Creates a new object and recursively copies all objects found in the original. This means it duplicates not just the top-level structure but also all nested structures.

How to create a deep copy of complex objects in Python?

To create a deep copy of complex objects in Python, you can use the deepcopy function from the copy module. Here is an example:

import copy

original = [[1, 2, 3], [4, 5, 6]]
deep_copied = copy.deepcopy(original)

# Modifying the copied object
deep_copied[0][0] = 99

print("Original:", original) # Output: Original: [[1, 2, 3], [4, 5, 6]]
print("Deep Copied:", deep_copied) # Output: Deep Copied: [[99, 2, 3], [4, 5, 6]]

How does shallow copy work in Python?

A shallow copy creates a new object but does not create copies of the nested objects within the original object. Instead, it inserts references to the same objects into the new object.

Example:

import copy

original = [[1, 2, 3], [4, 5, 6]]
shallow_copied = copy.copy(original)

# Modifying the copied object
shallow_copied[0][0] = 99

print("Original:", original) # Output: Original: [[99, 2, 3], [4, 5, 6]]
print("Shallow Copied:", shallow_copied) # Output: Shallow Copied: [[99, 2, 3], [4, 5, 6]]

What are the implications of copying mutable objects in Python?

When copying mutable objects, changes to the copied object can affect the original object, depending on whether a shallow or deep copy was used:

  • Shallow Copy: If you modify a mutable object within the shallow copied object, the change will reflect in the original object because they share the same reference.
  • Deep Copy: Modifications to mutable objects within the deep copied object do not affect the original object, as all objects are fully copied and independent.

How to use the copy module for deep and shallow copies in Python?

The copy module provides functions to create shallow and deep copies of objects:

  • Shallow Copy: Use copy.copy() to create a shallow copy.
  • Deep Copy: Use copy.deepcopy() to create a deep copy.


Similar Reads

Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Difference between Shallow and Deep copy of a class
Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep C
5 min read
MoviePy – Shallow copying Video File Clip
In this article we will see how we can shallow copy the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the o
2 min read
Deep dive into Parameters and Arguments in Python
There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. Parameters:A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Examp
3 min read
Avengers Endgame and Deep learning | Image Caption Generation using the Avengers EndGames Characters
Behold, Marvel Fans. Avengers are out there to save the Multiverse, so are we, ready to do whatever it takes to support them. In this article, we will use Deep Learning and computer vision for the caption generation of Avengers Endgame characters. We will start will the basics, explaining concepts and use a pre-trained model to implement the projec
14 min read
Create Homogeneous Graphs using dgl (Deep Graph Library) library
In this article, we will create Homogeneous Graphs using dgl (Deep Graph Library) library. Graphs are nothing but collections of Nodes/Vertices and Edges. Also, Edges are nothing but Source nodes to Destination nodes. So all edges can be represented as (U, V) where U and V are nodes. G = (V, E) Package Required pip install dglWhat is Deep Graph Lib
3 min read
Talking Healthcare Chatbot using Deep Learning
Today in this article we are going to see how we can build a Talking Healthcare Chatbot using Deep Learning. It is recommended to know the basics of Deep Learning, the Intermediate stage of knowing Python, and the Theory of Neural Networks. Users should also be familiar with how to use the SpeechRecognition module and set it up. First, we need to i
14 min read
AI Driven Snake Game using Deep Q Learning
Content has been removed from this Article
1 min read
Select the right Weight for deep Neural Network in Pytorch
PyTorch has developed a strong and adaptable framework for creating deep neural networks (DNNs) in the field of deep learning. Choosing the proper weight for your model is an important component in designing an efficient DNN. Initialization of weights is critical in deciding how successfully your neural network will learn from input and converge to
11 min read
Kaiming Initialization in Deep Learning
Kaiming Initialization is a weight initialization technique in deep learning that adjusts the initial weights of neural network layers to facilitate efficient training by addressing the vanishing or exploding gradient problem. The article aims to explore the fundamentals of Kaiming initialization and it's implementation. What is Kaiming Initializat
7 min read
Next Word Prediction with Deep Learning in NLP
Identifying the most likely word to follow a given string of words is the basic goal of the Natural Language Processing (NLP) task of "next word prediction." This predictive skill is essential in various applications, including text auto-completion, speech recognition, and machine translation. Deep learning approaches have transformed NLP by attain
9 min read
Morphology Exploration in NLP using word_forms: A Deep Dive
Natural Language Processing (NLP) is a field constantly evolving, and a crucial component of its success is the ability to understand the structure and formation of words – morphology. The Python library word_forms emerges as a powerful tool in this domain, simplifying the extraction of morphological information from English words. This article del
5 min read
NumPy ndarray.copy() Method | Make Copy of a Array
The ndarray.copy() method returns a copy of the array. It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array. Example C/C++ Code # Python program explaining # numpy.ndarray.copy() function import numpy as geek x
2 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Python | Move or Copy Files and Directories
Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.copy(src, dst) # Copy files, but preserve metadata
3 min read
Copy And Replace Files in Python
In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, this operation is crucial for updating or maintaining
2 min read
Copy Files and Rename in Python
Copying and renaming files is a common task in programming, and Python provides several ways to accomplish this efficiently. In this article, we will explore some commonly used methods for copying files and renaming them: using the shutil module's copy() and pathlib module's Path class. Each method has its advantages, and choosing the right one dep
2 min read
set copy() in python
The copy() method returns a shallow copy of the set in python. If we use "=" to copy a set to another set, when we modify in the copied set, the changes are also reflected in the original set. So we have to create a shallow copy of the set such that when we modify something in the copied set, changes are not reflected back in the original set. Synt
2 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() method Syntax: dict.copy() Return: This method does
3 min read
Python | Ways to Copy Dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let's discuss a few ways to copy the
3 min read
Python | Pandas Index.copy()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.copy() function make a copy of this object. The function also sets the name and dtype attribute of the new object as that o
2 min read
Python | Pandas TimedeltaIndex.copy
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.copy() function make a copy of this TimedeltaIndex object. The function also sets the Name and dtype attributes on
2 min read
Python | Numpy matrix.copy()
With the help of Numpy matrix.copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix. Syntax : matrix.copy() Return : Return copy of matrix Example #1 : In this example we can see that with the help of matrix.copy() method we are making
1 min read
Python | Pandas tseries.offsets.DateOffset.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessDay.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessHour.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessDay.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessHour.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | shutil.copy() method
C/C++ Code # Python program to explain shutil.copy() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied su
5 min read
Article Tags :
Practice Tags :