How to Copy a List in Python: Simple Methods Explained
To copy a list in Python, you can use
list.copy(), slicing like list[:], or the list() constructor. These methods create a new list with the same elements, avoiding changes to the original list when you modify the copy.Syntax
Here are the common ways to copy a list in Python:
new_list = old_list.copy()- uses thecopy()method.new_list = old_list[:]- uses slicing to copy all elements.new_list = list(old_list)- uses thelist()constructor to create a copy.
Each creates a new list with the same items as the original.
python
old_list = [1, 2, 3] # Using copy() method new_list1 = old_list.copy() # Using slicing new_list2 = old_list[:] # Using list() constructor new_list3 = list(old_list)
Example
This example shows how changing the copied list does not affect the original list.
python
original = [10, 20, 30] copied = original.copy() copied.append(40) print("Original list:", original) print("Copied list:", copied)
Output
Original list: [10, 20, 30]
Copied list: [10, 20, 30, 40]
Common Pitfalls
A common mistake is to assign a list directly like new_list = old_list. This does not copy the list but makes both variables point to the same list. Changes to one will affect the other.
Also, these methods create a shallow copy. If the list contains other lists (nested lists), the inner lists are not copied but shared.
python
old_list = [[1, 2], [3, 4]] # Wrong: just assignment new_list = old_list new_list[0].append(99) print("Old list after change:", old_list) # Right: shallow copy new_list2 = old_list.copy() new_list2[0].append(100) print("Old list after shallow copy change:", old_list)
Output
Old list after change: [[1, 2, 99], [3, 4]]
Old list after shallow copy change: [[1, 2, 99, 100], [3, 4]]
Quick Reference
| Method | Description | Example |
|---|---|---|
| copy() | Creates a shallow copy of the list | new_list = old_list.copy() |
| Slicing | Copies all elements using slice syntax | new_list = old_list[:] |
| list() | Creates a new list from an iterable | new_list = list(old_list) |
| Assignment | Does NOT copy, just references the same list | new_list = old_list |
Key Takeaways
Use list.copy(), slicing, or list() to create a new list copy.
Direct assignment copies only the reference, not the list itself.
These methods create shallow copies; nested lists remain shared.
Modifying the copied list does not affect the original list.
For deep copies of nested lists, use the copy module's deepcopy.