How do I clone a list so that it doesn't change unexpectedly after assignment?
Codemia Knowledge Hub ·
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 put a time delay in a Python script?
- Manually raising (throwing) an exception in Python
- What is the difference between __str__ and __repr__?
- >, <, >= and <= don''t work with filter in Django
- __init__ got an unexpected keyword argument 'cachedir' when importing top2vec
- __str__ versus __unicode__
- _csv.Error field larger than field limit 131072
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.