Appearance
How do I clone a list so that it doesn't change unexpectedly after assignment?
There are several ways to make a copy of a list in Python:
- Using the
list.copy()method (Python 3.3+):
Using the .copy() method
python
original_list = [1, 2, 3]
new_list = original_list.copy()
print(new_list)- Using the
list()constructor:
Using the list() constructor
python
original_list = [1, 2, 3]
new_list = list(original_list)
print(new_list)- Using slicing:
Using list slicing
python
original_list = [1, 2, 3]
new_list = original_list[:]
print(new_list)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
- Using
copy.copy():
Using copy.copy()
python
import copy
original_list = [1, 2, 3]
new_list = copy.copy(original_list)
print(new_list)- Using
copy.deepcopy():
Using copy.deepcopy()
python
import copy
original_list = [1, 2, 3]
new_list = copy.deepcopy(original_list)
print(new_list)Methods 1 through 4 create a shallow copy of the list, meaning that if the original list contains any mutable objects (like nested lists), changes to those objects will be reflected in both the original and the copy.
Method 5 creates a deep copy of the list, which means that the copy is completely independent of the original, including any mutable objects it contains.
Which method you use will depend on your specific needs. If you just want to create a new list with the same elements as the original, methods 1 through 4 will work. If you need to create a completely independent copy of the list, including any mutable objects it contains, you should use copy.deepcopy().