How to Copy Lists in Python: Using the Copy Method
Learn how to create an actual copy of a list in Python rather than just referencing the original list. Discover why using list2 = list1
only creates a reference, and explore how to use the built-in copy()
method to make a true copy of a list. Get practical examples to understand the difference and ensure changes in the copied list don't affect the original list.
Python - Copy Lists
Copy a List
You cannot copy a list simply by typing list2 = list1
, because list2
will only be a reference to list1
. Any changes made to list1
will also reflect in list2
.
There are ways to make an actual copy of the list. One way is to use the built-in list method copy()
.
Example
Make a copy of a list using the copy()
method:
thislist = ["orange", "kiwi", "grape"]
mylist = thislist.copy()
print(mylist)
Output
['orange', 'kiwi', 'grape']
Another way to make a copy is to use the built-in list()
method.
Example
Make a copy of a list using the list()
method:
thislist = ["orange", "kiwi", "grape"]
mylist = list(thislist)
print(mylist)
Output
['orange', 'kiwi', 'grape']