Copy a List
Writing list2 = list1 does not give you a copy. list2 becomes just a reference to list1, so any change you make in list1 shows up in list2 as well.
Use the copy() method
Lists come with a built-in copy() method that does this job properly.
Example
Create a copy by calling the copy() method:
Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry.
Make a copy of the list using the copy() method and print the copy.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Use the list() Constructor
The built-in list() constructor can make a copy of a list as well.
Example
Create a copy by calling the list() constructor:
Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry.
Make a copy of the list using the list() method and print the copy.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Use the slice Operator
A third option for copying a list is the : (slice) operator.
Example
Create a copy of the list by slicing with the : operator:
Prompt
Write a Python program that creates a list with three fruits: apple, banana, cherry.
Make a copy of the list using the slice operator [:] and print the copy.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
print(mylist)