Copying Lists in Python
List Satellite
Copy Lists Correctly
Cloning a list sounds simple, but references make it tricky. Learn all the options and when to use them.
Techniques
| Method | Example | Notes |
|---|---|---|
| Slice | copy = original[:] | Shallow copy |
.copy() | copy = original.copy() | Shallow copy |
list() | copy = list(original) | Shallow copy |
copy.copy() | copy.copy(original) | Explicit shallow copy |
All shallow copies duplicate the list container but keep references to the same elements.
Deep copy
import copy
deep = copy.deepcopy(nested)
Use deep copy when nested structures must be independent. Recursive objects or custom classes may need __deepcopy__ defined.