Copy Lists
Copying lists in Python is an important concept because lists are mutable.
If you copy a list incorrectly, changes in one list may unexpectedly affect another.
This topic explains all correct and incorrect ways to copy lists, with clear examples.
Why Copying Lists Matters
Lists store references, not values.
So assigning one list to another does not create a new list.
python
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
Both variables point to the same list.
Copy a List Using copy()
The
copy() method creates a shallow copy of the list.python
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)
Copy a List Using list() Constructor
python
a = [10, 20, 30]
b = list(a)
b.append(40)
print(a)
print(b)
Copy a List Using Slicing
python
a = [5, 6, 7]
b = a[:]
b.append(8)
print(a)
print(b)
Shallow Copy vs Deep Copy
Shallow Copy (Important Concept)
A shallow copy copies the outer list only.
python
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
print(a)
print(b)
Both lists are affected.
Deep Copy Using copy Module
A deep copy copies all nested objects.
python
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0].append(99)
print(a)
print(b)
Copy Using Loop
python
a = [1, 2, 3]
b = []
for x in a:
b.append(x)
print(b)
Copy Using List Comprehension
python
a = [10, 20, 30]
b = [x for x in a]
print(b)
Compare Copied Lists
python
a = [1, 2, 3]
b = a.copy()
print(a == b)
print(a is b)
Common Mistakes
Using Assignment Instead of Copy
python
a = [1, 2]
b = a
This does not create a copy.
Forgetting Deep Copy for Nested Lists
python
a = [[1, 2], [3, 4]]
b = a[:]
This is still a shallow copy.
When to Use Which Method
| Method | Use Case |
|---|---|
copy() | Simple, clean shallow copy |
list() | Shallow copy from iterable |
Slicing ([:]) | Quick shallow copy |
deepcopy() | Nested lists |
| Loop / comprehension | Custom logic |
Summary
- Assignment does not copy lists
copy(),list(), and slicing create shallow copies- Shallow copies share nested objects
deepcopy()creates independent copies- Choose method based on list structure and use case