Copy Lists in python
You cannot copy a list simply by typing , because: list2 = list1 will only be a reference to list2, and changes made in list1 will automatically also be made in list1.
list2
Use the copy() method
You can use the built-in List method copy() to copy a list.
Example
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:
['apple', 'banana', 'cherry']
Use the list() method
Another way to make a copy is to use the built-in method list().
Example
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output:
['apple', 'banana', 'cherry']
Use the slice Operator
You can also make a copy of a list by using the (slice) operator.
:
Example
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
print(mylist)
Output:
['apple', 'banana', 'cherry']