Python – Copy Lists
In Python, copying a list isn't as simple as using =
, which only creates a reference to the original list. If you want to make a real copy, Python provides several effective methods.
Why Not Use =
Using the assignment operator (=
) doesn't copy a list. It only creates another reference to the same list.
Example:
list1 = ["apple", "banana", "cherry"]
list2 = list1
list2.append("orange")
print(list1)
Output:
['apple', 'banana', 'cherry', 'orange']
Both list1
and list2
point to the same object.
1. Copy Using list.copy()
Creates a shallow copy of the list.
Example:
original = ["apple", "banana", "cherry"]
copied = original.copy()
copied.append("orange")
print("Original:", original)
print("Copied:", copied)
Output:
Original: ['apple', 'banana', 'cherry']
Copied: ['apple', 'banana', 'cherry', 'orange']
Best for shallow (non-nested) lists.
2. Copy Using list()
Constructor
Another way to make a shallow copy.
Example:
original = ["apple", "banana", "cherry"]
copied = list(original)
print(copied)
Output:
['apple', 'banana', 'cherry']
3. Copy Using Slicing ([:]
)
A clean and common method to copy lists.
Example:
original = [1, 2, 3, 4]
copied = original[:]
print(copied)
Output:
[1, 2, 3, 4]
4. Copy Using copy
Module (deepcopy()
for Nested Lists)
Use copy.deepcopy()
to copy nested lists (deep copy).
Example:
import copy
original = [[1, 2], [3, 4]]
deep_copied = copy.deepcopy(original)
deep_copied[0][0] = 99
print("Original:", original)
print("Deep Copy:", deep_copied)
Output:
Original: [[1, 2], [3, 4]]
Deep Copy: [[99, 2], [3, 4]]
Use this when copying lists with nested lists or complex objects.
Summary Table
Method | Type | Use Case |
---|---|---|
list.copy() | Shallow | Basic lists |
list() constructor | Shallow | Alternate shallow copy |
[:] slicing | Shallow | Most common shortcut |
copy.deepcopy() | Deep | Nested or complex structures |
= assignment | Reference | Do not use for copying |