Copying lists can be done in a couple of ways, depending on whether you need a shallow copy (a new list with references to the same elements) or a deep copy (a new list with entirely new copies of all nested objects). Here’s a look at each method:
A shallow copy of a list creates a new list with references to the same objects as the original list, so changes to mutable elements within the original list will affect the copy (and vice versa). However, changes to the list structure itself (like adding or removing elements) won’t impact the other list.
copy()
The copy()
method is available for lists and creates a shallow copy of the list.
original_list = [1, [2, 3], 4]
shallow_copy = original_list.copy()
# Modifying a mutable element (inner list) in the original
original_list[1][0] = "changed"
print(shallow_copy) # Output: [1, ["changed", 3], 4]
[:]
)Slicing with [:]
is another way to create a shallow copy.
original_list = [1, [2, 3], 4]
shallow_copy = original_list[:]
A deep copy, on the other hand, creates a completely new copy of the list and all objects within it, so changes to elements in the original list won’t affect the copy at all. This method is particularly useful when the list contains nested lists or other mutable objects.
copy.deepcopy()
The deepcopy()
function from Python’s copy
module creates a deep copy.
import copy
original_list = [1, [2, 3], 4]
deep_copy = copy.deepcopy(original_list)
# Modifying a mutable element (inner list) in the original
original_list[1][0] = "changed"
print(deep_copy) # Output: [1, [2, 3], 4] - remains unchanged
list.copy()
or [:]
for a shallow copy where elements refer to the same objects as in the original list.copy.deepcopy()
for a completely independent copy that won’t be affected by changes in the original list’s nested objects.