• Python »
  • 3.13.0 Documentation »
  • The Python Standard Library »
  • Data Types »
  • copy — Shallow and deep copy operations
  • Theme Auto Light Dark |

copy — Shallow and deep copy operations ¶

Source code: Lib/copy.py

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Interface summary:

Return a shallow copy of obj .

Return a deep copy of obj .

Creates a new object of the same type as obj , replacing fields with values from changes .

Added in version 3.13.

Raised for module specific errors.

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.

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

keeping a memo dictionary of objects already copied during the current copying pass; and

letting user-defined classes override the copying operation or the set of components copied.

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

Shallow copies of dictionaries can be made using dict.copy() , and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:] .

Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__() .

Called to implement the shallow copy operation; no additional arguments are passed.

Called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__ implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.

Function copy.replace() is more limited than copy() and deepcopy() , and only supports named tuples created by namedtuple() , dataclasses , and other classes which define method __replace__() .

This method should create a new object of the same type, replacing fields with values from changes .

Discussion of the special methods used to support object state retrieval and restoration.

Table of Contents

  • __deepcopy__()
  • __replace__()

Previous topic

types — Dynamic type creation and names for built-in types

pprint — Data pretty printer

  • Report a Bug
  • Show Source

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, certification courses.

Created with over a decade of experience and thousands of feedback.

Python Introduction

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python List copy()

Python Dictionary copy()

Python Set copy()

Python List clear()

  • Python Set union()

Python Shallow Copy and Deep Copy

Copy an object in python.

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator.

Example 1: Copy using = operator

When we run above program, the output will be:

As you can see from the output both variables old_list and new_list shares the same id i.e 140673303268168 .

So, if you want to modify any values in new_list or old_list , the change is visible in both.

Essentially, sometimes you may want to have the original values unchanged and only modify the new values or vice versa. In Python, there are two ways to create copies:

  • Shallow Copy

To make these copy work, we use the copy module.

  • Copy Module

We use the copy module of Python for shallow and deep copy operations. Suppose, you need to copy the compound list say x . For example:

Here, the copy() return a shallow copy of x . Similarly, deepcopy() return a deep copy of x .

A shallow copy creates a new object which stores the reference of the original elements.

So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. This means, a copy process does not recurse or create copies of nested objects itself.

Example 2: Create a copy using shallow copy

When we run the program , the output will be:

In above program, we created a nested list and then shallow copy it using copy() method.

This means it will create new and independent object with same content. To verify this, we print the both old_list and new_list .

To confirm that new_list is different from old_list , we try to add new nested object to original and check it.

Example 3: Adding [4, 4, 4] to old_list, using shallow copy

When we run the program, it will output:

In the above program, we created a shallow copy of old_list . The new_list contains references to original nested objects stored in old_list . Then we add the new list i.e [4, 4, 4] into old_list . This new sublist was not copied in new_list .

However, when you change any nested objects in old_list , the changes appear in new_list .

Example 4: Adding new nested object using Shallow copy

In the above program, we made changes to old_list i.e old_list[1][1] = 'AA' . Both sublists of old_list and new_list at index [1][1] were modified. This is because, both lists share the reference of same nested objects.

A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements.

Let’s continue with example 2. However, we are going to create deep copy using deepcopy() function present in copy module. The deep copy creates independent copy of original object and all its nested objects.

Example 5: Copying a list using deepcopy()

In the above program, we use deepcopy() function to create copy which looks similar.

However, if you make changes to any nested objects in original object old_list , you’ll see no changes to the copy new_list .

Example 6: Adding a new nested object in the list using Deep copy

In the above program, when we assign a new value to old_list , we can see only the old_list is modified. This means, both the old_list and the new_list are independent. This is because the old_list was recursively copied, which is true for all its nested objects.

Table of Contents

  • Copy an Object in Python

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Library

Python Simplified

PythonSimplifiedcomLogo

The Ultimate Guide to Shallow Copy and Deep Copy in Python

  • May 31, 2021
  • Author - Chetan Ambi
  • Category - Python

Shallow & Deep Copy

Table of Contents

Introduction

When writing a program, we often want to create a copy of an object (int, float, list, tuple, dictionary, etc.). Because we want to use the copy (new) object without changing the content of the original. 

There are a number of ways you can create a copy of the object in Python. But, beware! Most of these methods create a shallow copy that you don’t want. But what you should need in this scenario is a deep copy .

So, what are these different methods of creating a copy of an object? What are shallow copy and deep copy? We are going to answer all these questions in this article. 

Let’s first understand that the assignment operator (=) does not create a copy (new) object. It just creates a binding between the copy (new) object and the original object (i.e. both objects share the same memory address ). But this doesn’t make difference for immutable objects such as int, float, decimal, bool, tuple, etc. because we can’t modify the immutable objects. 

Shallow Copy

A shallow copy creates a copy of the given compound object and while doing so it inserts the references to the objects found in the original. You will understand this definition once you go through this section.

There are many ways you can create shallow copies in Python. Let’s look at 6 different ways to create shallow copies in the below  — 

Notice that the memory location of both the objects ( my_list1 and my_list2 ) in all the methods shown below. As you can see, id(my_list1) and id(my_list2) return two different memory addresses. It indicates that a new object (copy) has been created.

The id() function returns address of the object. It is briefly covered here if you want to take a quick look.

List comprehension

Copy method

Constructor

Copy module

In all these methods if you try to modify (add/delete/change) an element in my_list1 or my_list2 , you expect the other list not to get updated. And that’s exactly what happens. This is because we have used a list where the elements of the list are immutable. For example, in my_list = [10,20,30,40,50] , the elements were immutable. Let’s see an example to confirm this.

Now, say you appended 60 to my_list2 . As you can see this didn’t modify the my_list1 . Because my_list1 and my_list2 are two different objects. 

So far so good. The copy operation is working exactly how we think it should. What if the original object (ex. list) has a nested structure (lists within the list) and you try to modify these mutable elements? What happens then? 

In the below example, my_list1 has a nested structure. Meaning the individual elements of my_list1 are also lists. Next, say you created my_list2 using any of the above-mentioned 6 methods. This is what it looks like visually. Though my_list1 and my_list2 are two different objects, their contents are sharing the same memory address.

shallow copy example image

Let’s confirm this programmatically. The id() function clearly shows that my_list1 and my_list2 are two different objects. 

But note that if the elements of the list are mutable, then share the same memory address as you can see below. 

Since they share the same memory address, if you modify my_list2[0] or my_list2[1] , the same changes will get reflected in my_list1 as well even though we are not intended to do that. But that is not what we want. Right? We want a real clone or copy that doesn’t affect the original. So, how do you handle this? That’s where deep copy comes into the picture.

A deep copy creates a copy of the given compound object and while doing so it recursively inserts copies of the objects found in the original. 

To create a deep copy of the object, you need to use deepcopy() method from the copy module. Let’s take the same example, we covered in the shallow copy section. 

As you can see from the code output and diagram, with deepcopy() we are able to overcome the issue with the shallow copy. Notice that nested elements don’t share the same address anymore. 

deep copy example image

Arbitrary Python Objects

In all the methods above, we have used a list for the demonstration. In fact, you can use any mutable type list, set, dictionary, or arbitrary Python object. Let’s look at an example of an arbitrary object below. 

Shallow copy: In the below example, we first created object c of MyClass and then created a shallow copy c1 . As you can see, even though both c (original object ) and shallow copy object c1 are different objects, their contents share the same memory. Note x[0] is [1,2] and x[1] is [3,4].

Since we are dealing with a shallow copy, when we appended [5,6] to original object c , the copy object c1 also got updated as expected.

Deep copy: Continuing the same example from above, we have created a deep copy c2 of the object c . Both original object c and copy object c2 are two different objects. Since it was a deep copy, instead of sharing the same memory, a real copy (clone) of the objects is created. As you can see the elements within c and c2 don’t share the same memory.

Hence, even though we change the content of c, it won’t be reflected in the copy object c2. 

In this article, we have understood shallow copy and deep copy in Python with examples. We have gone through 6 different ways of creating shallow copies. In order to create deep copy, we used copy module. In the last section, we saw that we can create shallow copy and deep copy on Python arbitrary objects as well.

Hope this answers all your doubts about shallow copy and deep copy in Python. Please do let us know if you have any questions in the comments section.

Chetan Ambi

Chetan Ambi

COMMENTS

  1. copy — Shallow and deep copy operations — Python 3.13.0 ...

    This module provides generic shallow and deep copy operations (explained below). Interface summary: copy.copy(obj) ¶. Return a shallow copy of obj. copy.deepcopy(obj[, memo]) ¶. Return a deep copy of obj. copy.replace(obj, /, **changes) ¶. Creates a new object of the same type as obj, replacing fields with values from changes.

  2. copy in Python (Deep Copy and Shallow Copy) - GeeksforGeeks

    copy in Python (Deep Copy and Shallow Copy) 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 ...

  3. python - What is the difference between shallow copy ...

    Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies:. The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  4. Python Shallow Copy and Deep Copy (With Examples) - Programiz

    Copy an Object in Python. In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator ...

  5. Shallow vs Deep Copying of Python Objects

    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 ...

  6. Array Copying in Python - GeeksforGeeks

    There are 3 ways to copy arrays : Simply using the assignment operator. Shallow Copy; Deep Copy; Assigning the Array. We can create a copy of an array by using the assignment operator (=). Syntax : new_arr = old_ arr. In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use ...

  7. Assignment vs. Shallow Copy vs. Deep Copy in Python

    Deep Copy. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. Creating a deep copy is slower because you are making new copies for everything. In this, rather than just copying the address of the compound objects, it simply makes a full copy of all the list’s ...

  8. The Ultimate Guide to Shallow Copy and Deep Copy in Python

    Deep Copy. A deep copy creates a copy of the given compound object and while doing so it recursively inserts copies of the objects found in the original. To create a deep copy of the object, you need to use deepcopy () method from the copy module. Let’s take the same example, we covered in the shallow copy section.

  9. Assignment, Shallow Copy, Or Deep Copy? | by Weilin Li ...">Assignment, Shallow Copy, Or Deep Copy? | by Weilin Li ...

    3. from copy import copy, deepcopy. The goal of this article is to describe what will happen in memory when we. Assign a variable B = A , Shallow copy it C = copy(A) , or. Deep copy it D = deepcopy(A). I first describe a bit about memory management and optimization in Python. After laying the ground, I explain the difference between assignment ...

  10. copy in Python (Deep Copy and Shallow Copy) - GeeksforGeeks">copy in Python (Deep Copy and Shallow Copy) - GeeksforGeeks

    In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object.