Python - Copy Lists
Copy a List
You cannot copy a list simply by typinglist2 = list1
, because:list2
will only be areference tolist1
, and changes made inlist1
will automatically also be made inlist2
.
Use the copy() method
You can use the built-in List methodcopy()
to copy a list.
Example
Make a copy of a list with thecopy()
method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Try it Yourself »mylist = thislist.copy()
print(mylist)
Use the list() method
Another way to make a copy is to use the built-in methodlist()
.
Example
Make a copy of a list with thelist()
method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Try it Yourself »mylist = list(thislist)
print(mylist)
Use the slice Operator
You can also make a copy of a list by using the:
(slice) operator.
Example
Make a copy of a list with the:
operator:
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
print(mylist)
Try it Yourself »mylist = thislist[:]
print(mylist)