How to copy a List in Python without side effects
Learn different ways to copy/clone a List in Python so that it doesn't change unexpectedly.
Learn different ways to copy/clone a List in Python so that it doesn't change unexpectedly.
When copying Lists (and other collection data types) in Python, we have to be careful.
When we simply use the copy assignment we only copy the reference to the List:
a = [1, 2, 3]
b = a
Both objects point to the same memory location, so changing one List also affects the other one!
b.append(4)
print(b) # [1, 2, 3, 4]
print(a) # [1, 2, 3, 4]
So how do we properly clone a List in Python?
#more
There are different ways to make an actual copy of 1-level deep Lists. Read on to find out how to clone nested Lists as well.
Use List slicing to clone a List¶
b = a[:]
Use list.copy()
to clone a List¶
b = a.copy()
Use the list()
function to clone a List¶
b = list(a)
Use copy.copy()
to clone a List¶
import copy
b = copy.copy(a)
Shallow vs. Deep copying¶
All the above mentioned ways do not produce side effects for 1 level deep Lists:
a = [1, 2, 3]
b = a[:]
# or:
# b = a.copy()
# b = list(a)
# b = copy.copy(a)
b.append(4)
print(b) # [1, 2, 3, 4]
print(a) # [1, 2, 3]
Warning
However, this still does not copy all inner elements for nested Lists!
We only created a so-called shallow copy.
Let's say we have a List of Lists. If we make a copy with one of the above methods and change the inner elements, it still affects the other List as well:
a = [[1, 2], [3, 4]]
b = a[:]
# or:
# b = a.copy()
# b = list(a)
# b = copy.copy(a)
b[0].append(99)
print(b) # [[1, 2, 99], [3, 4]]
print(a) # [[1, 2, 99], [3, 4]]
In this case, we have to make a deep copy to clone all inner elements, too. You can learn more about Shallow vs. Deep Copying in Python in this article.
Use copy.deepcopy()
to clone a List and all its elements¶
To make a full clone of the List and all its inner elements, we have to use copy.deepcopy()
. This is obviously the slowest method, but guarantees there are no side effects after copying the List.
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0].append(99)
print(b) # [[1, 2, 99], [3, 4]]
print(a) # [[1, 2], [3, 4]]
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*