Copy Lists
Copy Methods
There are multiple ways to copy lists in Python, each with different implications:
- **Slice copying** (`lst[:]`): Creates a shallow copy.
- **list.copy() method**: Shallow copy, available in Python 3.3+.
- **list() constructor**: Shallow copy from an existing iterable.
- **copy.deepcopy()**: Recursively copies all nested structures.
- **Assignment** (`=`): Creates a reference, not a true copy.
Example
original = [1, 2, [3, 4]]
# Shallow copies
slice_copy = original[:]
method_copy = original.copy()
constructor_copy = list(original)
# Deep copy
import copy
deep_copy = copy.deepcopy(original)
print(original)
print(slice_copy)
print(method_copy)
print(constructor_copy)
print(deep_copy)
Output
[1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]]
Shallow vs Deep Copy
Shallow copies duplicate the outer list but keep references to the same inner objects. Deep copies recursively copy everything, creating completely independent objects.
Example
# Modify shallow copy
slice_copy[0] = 99 # Doesn't affect original
slice_copy[2][0] = 88 # Affects original (nested list shared)
# Modify deep copy
deep_copy[0] = 77
deep_copy[2][0] = 66 # Does not affect original
print("Original:", original)
print("Shallow:", slice_copy)
print("Deep:", deep_copy)
Output
Original: [1, 2, [88, 4]] Shallow: [99, 2, [88, 4]] Deep: [77, 2, [66, 4]]
When to Use Each
Choosing the right copy method depends on the structure of your list and whether nested objects need to be independent.
Copy Type | Use When | Example |
---|---|---|
Assignment | You want a reference to the same list | view = original |
Shallow Copy | List contains only immutable or flat elements | copy = original[:] |
Deep Copy | List contains nested mutable structures that must be independent | copy = deepcopy(original) |