From this tutorial, you will be learning about Python list copy method. You will see how to use it with lists with the help of examples.
Note: The syntax used here is for Python 3. You may modify it to use with other versions of Python.
Python List Copy
To Learn Python from Scratch – Read Python Tutorial
List Copy Method
The Copy method performs the shallow copy of a list. The syntax used is:
It doesn’t accept any argument and also doesn’t return a value. It produces a shallow copy and exits after it.
Please don’t get confused the List Copy method with the Copy module. The latter provides developers with the ability to create both Shallow copy and deep copy.
The List copy only provides the ability to create a shallow copy. Next, you will see the difference between Shallow copy and Deep copy.
Difference: Shallow Copy Vs. Deep Copy
A shallow copy is one in which a new object gets created which stores the reference of another object.
While the deep copy produces a new object that stores all references of another object making it another list separate from the original one.
Thus when you make a change to the deep copy of a list, the old list doesn’t get affected. But the same does get changed during the shallow copying.
List Copy Mechanism
When we call the copy method, it takes the old list and creates a new object and stores in it all the references to the old one.
The following flowchart attempts to simplify it for you:
1. Creating a copy of List containing elements
Natural_Numbers = [1,2,3,4,5,6,7,8,9] New_Copy = Natural_Numbers.copy() print (New_Copy)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Creating a copy of List containing strings
Strings = ["Linux", "Windows", "MacOS", "Chrome OS"] New_Strings = Strings.copy() print (New_Strings)
['Linux', 'Windows', 'MacOS', 'Chrome OS']
3. Creating a copy of an empty list
List =  New_List = List.copy() print (New_List)
4. Creating a copy of a non-existent List
New_List = List.copy()
Traceback (most recent call last): File "C:\Python\Python35\listcopy.py", line 1, in <module> New_List = List.copy() NameError: name 'List' is not defined