E0_copy is not a deep copy. You don't make a deep copy using list(). (Both list(...) and testList[:] are shallow copies, as well as testList.copy().)

You use copy.deepcopy(...) for deep copying a list.

copy.deepcopy(x[, memo])

Return a deep copy of x.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

To explain, list(...) does not recursively make copies of the inner objects. It only makes a copy of the outermost list, while still referencing the same inner lists, hence, when you mutate the inner lists, the change is reflected in both the original list and the shallow copy. You can see that shallow copying references the inner lists by checking that id(a[0]) == id(b[0]) where b = list(a).

Answer from Sukrit Kalra on Stack Overflow
🌐
Python
docs.python.org › 3 › library › copy.html
copy — Shallow and deep copy operations
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.
Top answer
1 of 10
416

E0_copy is not a deep copy. You don't make a deep copy using list(). (Both list(...) and testList[:] are shallow copies, as well as testList.copy().)

You use copy.deepcopy(...) for deep copying a list.

copy.deepcopy(x[, memo])

Return a deep copy of x.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

To explain, list(...) does not recursively make copies of the inner objects. It only makes a copy of the outermost list, while still referencing the same inner lists, hence, when you mutate the inner lists, the change is reflected in both the original list and the shallow copy. You can see that shallow copying references the inner lists by checking that id(a[0]) == id(b[0]) where b = list(a).

2 of 10
104

In Python, there is a module called copy with two useful functions:

import copy
copy.copy()
copy.deepcopy()

copy() is a shallow copy function. If the given argument is a compound data structure, for instance a list, then Python will create another object of the same type (in this case, a new list) but for everything inside the old list, only their reference is copied. Think of it like:

newList = [elem for elem in oldlist]

Intuitively, we could assume that deepcopy() would follow the same paradigm, and the only difference is that for each elem we will recursively call deepcopy, (just like mbguy's answer)

but this is wrong!

deepcopy() actually preserves the graphical structure of the original compound data:

a = [1,2]
b = [a,a] # there's only 1 object a
c = deepcopy(b)

# check the result
c[0] is a # False, a new object a_1 is created
c[0] is c[1] # True, c is [a_1, a_1] not [a_1, a_2]

This is the tricky part: during the process of deepcopy(), a hashtable (dictionary in Python) is used to map each old object ref onto each new object ref, which prevents unnecessary duplicates and thus preserves the structure of the copied compound data.

Official docs

Discussions

deep copy of list in python - Stack Overflow
pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create an account to view your personalized homepage. Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Save this question. Show activity on this post. ... I tried to make a deep copy of a list ... More on stackoverflow.com
🌐 stackoverflow.com
Why choose to copy a list with slices instead of copy(), deepcopy(), or list()??
Does Python just have multiple ways to copy a list in the same way??? Although most of the approaches mentioned can be used to copy lists, that doesn't mean that's what they're for! Every operation has a different purpose: Using the slicing technique The purpose of slicing is to select an arbitrary subset of a list. Slices can be used to either obtain a copy of this subset, or to modify the selected subset. For example: foo = [1, 2, 3, 4, 5] print(foo[1:3]) # will print: [2, 3] foo[1:3] = ['a', 'b', 'c', 'd'] print(foo) # will print: [1, a, b, c, d, 4, 5] 2. Using the extend() method The purpose of extend is to add a whole other collection of items onto the end of an existing list. Although slicing can be used for this too, .extend() is less error prone since you don't have to worry about calculating the correct indexes. 3. List copy using =(assignment operator) Geeksforgeeks is wrong here. The = operator doesn't make a copy. Rather, you simply have two different variables refer to the exact same list. 4. Using the method of Shallow Copy Python's copy module wasn't made for lists. The copy() and deepcopy() functions are able to make copies of any arbitrary Python object. For example: from copy import copy class Person: def __init__(self, fname, lname): self.first_name = fname self.last_name = lname def print_greeting(self): print(f"Hello! My name is {self.first_name} {self.last_name}.") foo = Person("Jack", "Johnson") foo.print_greeting() # Will print: Hello! My name is Jack Johnson. bar = copy(foo) bar.print_greeting() # Will print: Hello! My name is Jack Johnson. foo.first_name = "John" foo.last_name = "Jackson" foo.print_greeting() # Will print: Hello! My name is John Jackson bar.print_greeting() # Will print: Hello! My name is Jack Johnson As you see, the copy operation actually made a copy of our Person object. The fact that it works for lists is just a consequence, but that doesn't make it the way of copying lists. 5. Using list comprehension List comprehensions are for constructing a new list based on the data in existing collections. Basically, they're meant to be a concise way to compose map() and filter() operations. You can also use it to quickly construct the cartesian product of multiple collections. 6. Using the append() method The append operation is simply for adding a single item onto a list. Nothing more. Manually writing your own for-loop to append items one by one is perhaps the most clucky & verbose way to copy a list. 7. Using the copy() method This is the only operation whose specific purpose is to copy a Python list. It's finely tuned just for that. Thus, it'll offer you the best performance. 8. Using the method of Deep Copy See #4. The deepcopy() function can make a copy of any arbitrary object, not just a list. 9. The list() function (not mentioned on geeksforgeeks). This is simply the list class constructor. Since 'list' is a class, it has to have a constructor, so might as well make it useful. It can accept any arbitrary collection - a set, a dictionary, a generator, a custom collection class, basically any object that has __iter__ defined on it. It uses the iterator interface to copy each item one by one into the new Python list. More on reddit.com
🌐 r/AskProgramming
11
1
November 3, 2022
copy vs deepcopy
Copy doesn't do exactly what deepcopy does: >>> a = [[1,2,3]] >>> b = a.copy() >>> b[0].append(4) >>> a [[1, 2, 3, 4]] >>> from copy import deepcopy >>> b = deepcopy(a) >>> b[0].append(5) >>> a [[1, 2, 3, 4]] >>> b [[1, 2, 3, 4, 5]] the point is that deepcopy creates new objects for everything, so the inner list will be recreated too. Thus modifying the inner list on a deep copy will not affect the source of the deep copy. More on reddit.com
🌐 r/learnpython
5
6
November 6, 2020
Why is copying a list so damn difficult in python?
This kind of confusion is mostly because you're thinking about python's object model wrong, or don't fully understand it. Perhaps this is a better way to think about things. Say you have this data structure: x = [ [1,2,3], [4,5,6], ] This statement creates 3 lists: 2 inner lists and one outer list. A reference to the outer list is then made available under the name x. When you execute this statement: y = x no data gets copied. You still have the same 3 lists in memory somewhere. All this did is make the outer list availible under the name y, in addition to its previous name x. When you execute this statement: y = list(x) or y = x[:] This creates a new list with the same contents as x. List x contained a reference to the 2 inner lists, so the new list will also contain a reference to those same 2 inner lists. Only one list is copied—the outer list. Now there are 4 lists in memory, the two inner lists, the outer list, and the copy of the outer list. The original outer list is available under the name x, and the new outer list is made available under the name y. The inner lists have not been copied! You can access and edit the inner lists from either x or y at this point! If you have a two dimensional (or higher) list, or any kind of nested data structure, and you want to make a full copy of everything, then you want to use the deepcopy() function in the copy module. Your solution also works for 2-D lists, as iterates over the items in the outer list and makes a copy of each of them, then builds a new outer list for all the inner copies. Hope this explanation helps. More on reddit.com
🌐 r/learnpython
30
9
March 16, 2013
🌐
Reddit
reddit.com › r/learnpython › shallow and deep copy
r/learnpython on Reddit: Shallow and Deep Copy
May 18, 2020 -

I am fairly new to the Python realm. What is the difference between shallow and deep copy? I know the theoritical part of it but Im not actually able to understand while practicing it.

1)Does the list.copy() work on shallow copy technique? How does it work?

2)How does it differ from the other copying techniques like the = operator; slicing [:] ; list() constructor?

I have experimented it on the interactive python using two lists list1 and list2. When using "List2 = List1", I was able to see changes I made to the List2 on the List1. Whereas copying the contents of List1 to the List2 using " List2 = List1.copy()" , didn't do so.

Please enlighten me! Thanks in advance!

🌐
GeeksforGeeks
geeksforgeeks.org › python › copy-python-deep-copy-shallow-copy
Deep Copy and Shallow Copy in Python - GeeksforGeeks
In Python, assignment statements create references to the same object rather than copying it. Python provides the copy module to create actual copies which offer functions for shallow (copy.copy()) and deep (copy. deepcopy ()) copies.
Published: February 5, 2026
🌐
Sentry
sentry.io › sentry answers › python › clone a list in python
Clone a List in Python With Shallow and Deep Copy | Sentry
1 week ago - To make a deep copy of the list, we must use the deepcopy function from Python’s built-in copy module:
🌐
SitePoint
sitepoint.com › python hub › copy lists
Python - Copy Lists | SitePoint — SitePoint
If you need to copy a list along with all its nested objects so they become fully independent, you’ll use deep copying. Python provides the copy module and its deepcopy() function for this purpose.
🌐
DataCamp
datacamp.com › tutorial › python-copy-list
Python Copy List: What You Should Know | DataCamp
August 13, 2024 - You can create a deep copy of a list using the deepcopy() function from the copy module. ... 7MMaster the basics of data analysis with Python in just four hours.
Find elsewhere
🌐
Real Python
realpython.com › lessons › deep-copy-list
Create a Deep Copy of a List (Video) – Real Python
So if you really want to create a deep copy of a list object—this is what a copy is called that also takes care of copying the contained objects—then you can do this by importing a module called copy from the standard library.
Published: January 23, 2024
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › make deep copy of list in python (example)
Make Deep Copy of Python List | Without Changing Copied Object
July 5, 2023 - 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.
🌐
Techie Delight
techiedelight.com › home › python › get a deep copy of a python list
Get a deep copy of a Python list | Techie Delight
July 7, 2026 - Consider the following code, where a shallow copy is made from a list of lists using the in-built copy function. Note that when the original list is changed, the change is reflected in both lists. ... To avoid this non-deterministic behavior, you need a deep copy of the list.
🌐
Delft Stack
delftstack.com › home › howto › python › deep copy list in python
How to Deep Copy a List in Python | Delft Stack
February 2, 2024 - Although list comprehension provides a more concise and Pythonic way to copy a list, it’s crucial to use the deepcopy() function for nested lists to ensure a true deep copy is created, preserving the independence of the original and copied lists.
🌐
Medium
medium.com › @stolzmo › understanding-shallow-and-deep-copies-in-python-36b53729c5a4
Understanding Shallow and Deep Copies in Python | by Mohamed Elaraby | Medium
June 28, 2024 - A deep copy creates a recursive copying process of the original collection object, so it populates copies of the child objects found in the original. That means that the new collection object and its elements are independent of the original.
Top answer
1 of 3
12

Your code does indeed succeed in creating a shallow copy. This can be seen by inspecting the IDs of the two outer lists, and noting that they differ.

>>> id(l)
140505607684808

>>> id(x)
140505607684680

Or simply comparing using is:

>>> x is l
False

However, because it is a shallow copy rather than a deep copy, the corresponding elements of the list are the same object as each other:

>>> x[0] is l[0]
True

This gives you the behaviour that you observed when the sub-lists are appended to.

If in fact what you wanted was a deep copy, then you could use copy.deepcopy. In this case the sublists are also new objects, and can be appended to without affecting the originals.

>>> from copy import deepcopy

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> xdeep = deepcopy(l)

>>> xdeep == l
True

>>> xdeep is l
False     <==== A shallow copy does the same here

>>> xdeep[0] is l[0]
False     <==== But THIS is different from with a shallow copy

>>> xdeep[0].append(10)

>>> print(l)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> print(xdeep)
[[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]

If you wanted to apply this in your function, you could do:

from copy import deepcopy

def processed(matrix,r,i):
    new_matrix = deepcopy(matrix)
    new_matrix[r].append(i)
    return new_matrix

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = processed(l,0,10)
print(x)
print(l)

If in fact you know that the matrix is always exactly 2 deep, then you could do it more efficiently than using deepcopy and without need for the import:

def processed(matrix,r,i):
    new_matrix = [sublist[:] for sublist in matrix]
    new_matrix[r].append(i)
    return new_matrix

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = processed(l,0,10)
print(x)
print(l)
2 of 3
1

What you're looking for is a deeper copy than what you did. A shallow copy only replaces the top layer, which does not seem to be what you're looking for. If you wanted a different outcome, try something like this:

def processed(matrix,r,i):
    matrix[r] = [*matrix[r], i]
    return matrix

l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x=l[:]
print(processed(x,0,10))
print(l)

The difference is that this makes two shallow copies - first to copy the outer list, and then the function copies the inner list before modifying it. The downside of this approach is that every call to processed now has extra overhead. If you wanted to do the copying all at once, you can do this:

def processed(matrix,r,i):
    matrix[r].append(i)
    return matrix

l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x=[inner[:] for inner in l]
print(processed(x,0,10))
print(l)

This copies two layers deep, using list comprehensions. Your structure only has two layers, so this fully copies the list.

🌐
Dataquest
dataquest.io › home › blog › how to copy a list in python (5 techniques w/ examples)
How to Copy a List in Python (5 Techniques w/ Examples)
March 6, 2023 - As mentioned earlier, the recursive deep copy produces a truly independent copy of the original list, which is why the inner lists in the original and copied lists point to two different memory locations. Obviously, any changes made to the inner list of one won't be reflected in the other. This tutorial discussed several different ways for copying a list in Python, such as the assignment operator, list slicing syntax, list.copy(), copy.copy(), and copy.deepcopy functions.
🌐
Kinsacreative
blog.kinsacreative.com › articles › python-deep-copy-list-lists
Python Deep Copy A List Of Lists In Order To Avoid Making Edits To The Original Nested List Object | Kinsa Creative Incorporated
February 18, 2024 - >>> list_1 = [[1, 2, 3, 4], [5, 6, 7, 8]] >>> # create list_2 as a copy of list_1 >>> list_2 = list_1[:] >>> # change the first outer element in the copied list >>> list_2[0] = 5 >>> # the first list will remain the same >>> list_1 [[1, 2, 3, 4], [5, 6, 7, 8]] >>> list_2 [5, [5, 6, 7, 8]] >>> # change the first element of the nested list in the copied list >>> list_2[1][0] = 'a' >>> # the first list will reflect the change >>> list_1 [[1, 2, 3, 4], ['a', 6, 7, 8]] >>> list_2 [5, ['a', 6, 7, 8]] Since the outer list contains objects (the inner list, or nested list, is an object) a deep copy is required in order to safely make edits to the nested list without those changes being reflected in the original:
🌐
Programiz
programiz.com › python-programming › shallow-deep-copy
Python Shallow Copy and Deep Copy (With Examples)
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.
🌐
Unstop
unstop.com › home › blog › copy python lists | shallow & deep copies (+code examples)
Copy Python Lists | Shallow & Deep Copies (+Code Examples)
January 7, 2025 - Use copy.deepcopy(): For deep copies, which recursively duplicate the elements, use the deepcopy() method from the copy module. We will discuss this in a later section. Be Mindful of Nested Structures: When working with lists containing nested ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Shallow and Deep Copy in Python: copy(), deepcopy() | note.nkmk.me
May 13, 2023 - In Python, you can make a shallow and deep copy using the copy() and deepcopy() functions from the copy module. A shallow copy can also be made with the copy() method of lists, dictionaries, and so on ...
🌐
Python Course
python-course.eu › python-tutorial › shallow-and-deep-copy.php
11. Shallow and Deep Copy | Python Tutorial | python-course.eu
June 29, 2022 - This means that both person1[1] ... problem is provided by the module copy. This module provides the method "deepcopy", which allows a complete or deep copy of an arbitrary list, i.e....