Python List copy() Method
In this tutorial, we are going to learn the Python list copy method. list copy function in Python allows creating a copy of the existing list. Sometimes we need to create a copy of the list, Then we have the best method to copy(), which is used to create a copy of the list.
Python list copy() method:
In Python, list copy() method is list built-in method which is used to create the copy of the list.
Syntax of the list copy() function:
Return type of the list copy() method:
The return type of the python list copy method is a new list, That does not modify the original list because the copy() method return a shallow copy of the list.
list copy() method parameters:
list copy method does not take any parameters.
You can create the copy of the list method using = operator for example:
old_list = [1, 2, 3, 4, 5] new_list = old_list
The problem with creating a copy of this way is that, if you modified the new_list, the old_list will also be modified.
new_list.append(6) print(new_list) print(old_list
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
However, if you need original list unchanged when the new list modified, you can use list copy function.
Copy list using copy() method.
fruits = ['apple', 'banana', 'cherry'] x = fruits.copy() print(x)
['apple', 'banana', 'cherry']
If you modified list x in the above example, fruits list not modified.
Copy list using slice syntax:
You can create create the copy of the list using slice syntax.
old_list = ['Python', 'C++', 'C', 'PHP'] new_list = old_list[:] new_list.append('Java') print('old_list:- ', old_list) print('new_list:- ', new_list)
old_list:- ['Python', 'C++', 'C', 'PHP'] new_list:- ['Python', 'C++', 'C', 'PHP', 'Java']
If you modified list new_list in the above example, old_list list not modified.
In this tutorial, you have learned about the Python list copy() method to create a copy of the existing list. Using slice syntax and list copy method you can create a copy of the existing list, which will be a shallow copy. When you use both methods to create a copy of the list, Then your new list becomes a new separate list.
I hope this article will help you. If you like this article please comment and share with your friends who want to learn Python programming from scratch to advanced.
For More Reference :- Click Here