How do I clone a list so that it doesn't change unexpectedly after assignment?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Python, when you assign a list to another variable using =, both variables point to the same list object. This means that changes made to one list will affect the other. To avoid this, you need to clone or copy the list to create a new independent object.
Here are several ways to properly clone a list:
1. Using the copy() Method (Shallow Copy)
The copy() method creates a shallow copy of the list.
Example:
Note:
For nested lists or other mutable objects, a shallow copy still references the same inner objects. Changes to the nested objects will affect both lists.
2. Using Slicing ([:])
Slicing creates a shallow copy of the list.
Example:
Like copy(), this method works well for shallow copies but won't clone nested objects.
3. Using list() Constructor
The list() constructor also creates a shallow copy of the list.
Example:
4. Using copy.deepcopy() (Deep Copy)
To completely clone a list, including nested objects, use the copy.deepcopy() function from the copy module. This creates a deep copy of the list.
Example:
- Shallow Copy (
copy()or slicing): Nested objects are shared. - Deep Copy (
copy.deepcopy()): Nested objects are fully cloned.
5. Using List Comprehension
If the list is flat (no nested objects), you can use list comprehension to clone it.
Example:
This creates a new list with the same items.
Comparison of Methods
| Method | Type | Supports Nested Objects |
list.copy() | Shallow Copy | ❌ No |
Slicing ([:]) | Shallow Copy | ❌ No |
list() Constructor | Shallow Copy | ❌ No |
copy.deepcopy() | Deep Copy | ✅ Yes |
| List Comprehension | Shallow Copy | ❌ No |
Summary
- Use
list.copy(), slicing ([:]), orlist()for shallow copies. - Use
copy.deepcopy()for deep copies (to handle nested objects). - Avoid simple assignment (
=) if you want independent copies of the list. 🚀
Related reading
- How do I concatenate two lists in Python?
- How do I make a flat list out of a list of lists?
- How do I put a time delay in a Python script?
- How do I split a list into equally-sized chunks?
- How slicing in Python works
- "Least Astonishment" and the Mutable Default Argument
- Manually raising (throwing) an exception in Python
- Understanding Python super() with __init__() methods
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.