Cloning a list in Python
Cloning a list in Python is essential to avoid unintended side effects, as simply assigning one list to another with the equals sign (=
) creates a reference, not a new copy [1]. This means both variables point to the same list object in memory, and modifying one will modify the other. To properly clone a list, you need to understand the difference between a shallow copy and a deep copy.
Shallow Copy: The Surface-Level Clone 🌊
A shallow copy creates a new list object, but it does not recursively copy the objects inside it. Instead, it copies the references to the objects from the original list [2].
- When to use: A shallow copy is sufficient and efficient when your list contains only immutable objects like strings, integers, or tuples. Changes to the new list (like adding or removing items) will not affect the original list.
There are three common ways to create a shallow copy:
1. Slicing ([:]
)
This is a concise and highly popular method for creating a shallow copy.
original_list = [1, 2, 3]
new_list = original_list[:]
new_list.append(4)
print(original_list)
# Output: [1, 2, 3]
print(new_list)
# Output: [1, 2, 3, 4]
This method creates a new list by slicing the original list from its first element to its last, effectively making a clone [3].
2. The list()
Constructor
The built-in list()
constructor can be used to create a new list from an existing iterable.
original_list = [1, 2, 3]
new_list = list(original_list)
new_list.append(4)
print(original_list)
# Output: [1, 2, 3]
print(new_list)
# Output: [1, 2, 3, 4]
3. The .copy()
Method
This is the most explicit and readable method for a shallow copy, introduced in Python 3.
original_list = [1, 2, 3]
new_list = original_list.copy()
new_list.append(4)
print(original_list)
# Output: [1, 2, 3]
print(new_list)
# Output: [1, 2, 3, 4]
All three methods achieve the same result for a simple, flat list.
The Shallow Copy Pitfall ⚠️
The problem with a shallow copy arises when your list contains mutable objects, such as other lists or dictionaries. Both the original and the new list will still share a reference to the nested mutable objects. If you modify a nested object in the new list, it will also be modified in the original list [4].
original_list = [1, [2, 3], 4]
shallow_copy = original_list[:]
shallow_copy[1].append(5)
print(original_list)
# Output: [1, [2, 3, 5], 4]
print(shallow_copy)
# Output: [1, [2, 3, 5], 4]
As you can see, modifying the nested list in shallow_copy
also changed original_list
because they both point to the same nested list in memory.
Deep Copy: The Full Clone 🧠
A deep copy creates a completely new, independent list. It recursively copies all objects, including all nested mutable objects, ensuring that no references are shared between the original and the new list [2].
- When to use: A deep copy is necessary when your list contains mutable objects and you need to ensure that changes to the new list will not affect the original list under any circumstances.
To perform a deep copy, you must use the deepcopy()
function from Python's built-in copy
module.
import copy
original_list = [1, [2, 3], 4]
deep_copy = copy.deepcopy(original_list)
deep_copy[1].append(5)
print(original_list)
# Output: [1, [2, 3], 4]
print(deep_copy)
# Output: [1, [2, 3, 5], 4]
Now, modifying the nested list in deep_copy
leaves the original_list
untouched. While powerful, deepcopy()
can be more memory-intensive and slower than a shallow copy, so use it only when needed [5].
Summary and Recommendations
Method | What it does | When to use |
---|---|---|
new = old | Creates a new reference. | Never for cloning! |
old[:] , list(old) , old.copy() | Shallow copy. | For lists of immutable objects. |
copy.deepcopy(old) | Deep copy. | For lists with nested mutable objects. |
Sources
- "How to Properly Clone a List in Python to Prevent Unintended Changes." Medium.
https://medium.com/@tempmailwithpassword/how-to-properly-clone-a-list-in-python-to-prevent-unintended-changes-23fd7d8481b4
- "Shallow Copy vs. Deep Copy." DataCamp.
https://www.datacamp.com/tutorial/python-copy-list
- "Python: How to Copy a List? (The Idiomatic Way)." Afternerd.
https://www.afternerd.com/blog/python-copy-list/
- "Shallow Copy vs Deep Copy in Python." JHK Infotech.
https://www.jhkinfotech.com/blog/shallow-copy-vs-deep-copy-in-python
- "Python List copy() Method." GeeksforGeeks.
https://www.geeksforgeeks.org/python/python-list-copy-method/
This video provides a great visual explanation of the difference between shallow and deep copying, which is highly recommended to understand the concept fully. Shallow vs Deep Copy in Python