π How to Copy a List in Python β Right Way vs Wrong Way! | TechTown.in
Copying lists in Python might seem simple β just assign it, right? Not quite! If youβre not careful, you might end up with two variables pointing to the same list instead of a copy.
In this guide, youβll learn the correct ways to copy a list in Python, including copy(), slicing, list(), and what not to do.
β The Wrong Way β Simple Assignment (=)
Many beginners assume this will copy the list:
list1 = ["apple", "banana", "cherry"]
list2 = list1
But this only creates a reference, not a new list. Both list1 and list2 now point to the same memory.
Example:
list2[0] = "mango"
print(list1) # ['mango', 'banana', 'cherry']
β They both changed β because they’re the same object.
β
1. Use copy() Method
This is the recommended and cleanest way to copy a list.
list1 = ["apple", "banana", "cherry"]
list2 = list1.copy()
list2[0] = "mango"
print(list1) # ['apple', 'banana', 'cherry']
print(list2) # ['mango', 'banana', 'cherry']
β
2. Use list() Constructor
Another safe way to copy:
list1 = ["a", "b", "c"]
list2 = list(list1)
β
list2 is now a new list object.
β
3. Use Slicing ([:])
You can also copy a list using slicing:
original = [1, 2, 3]
copy_list = original[:]
This creates a shallow copy of the list.
π Summary β How to Copy Lists in Python
| Method | Description | Creates New List? |
|---|---|---|
list2 = list1 | Reference (β οΈ not a real copy) | β No |
list1.copy() | Shallow copy (Pythonic way) | β Yes |
list(list1) | Constructor-based copy | β Yes |
list1[:] | Slice-based copy | β Yes |
π§ What is a Shallow Copy?
All these methods create a shallow copy, meaning:
- The outer list is copied, but
- If the list contains nested lists, only the references are copied.
Example:
a = [[1, 2], [3, 4]]
b = a.copy()
b[0][0] = 99
print(a) # [[99, 2], [3, 4]]
π To fully copy nested lists, use copy.deepcopy() (from the copy module).
π Final Thoughts
Copying a list properly ensures you avoid unintended side effects in your programs. If you’re working with simple (non-nested) lists, copy(), list(), or slicing ([:]) are your best friends.
π Learn more Python list tips and tricks at TechTown.in