Menu Close
python list copy() method

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.

In the previous tutorial, we have seen the Python list append method and list clear method.
In this guide, we will learn how to create a copy of the list using different-2 methods.

Python list copy() method:

In Python, list copy() method is a list built-in method that is used to create the copy of the list.

Syntax of the list copy() function:

list.copy()

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 a copy of the list method using the = 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

Output

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

However, if you need the original list unchanged when the new list is modified, you can use the list copy function.

Copy list using copy() method.

Example:

fruits = ['apple', 'banana', 'cherry']
x = fruits.copy()
print(x)

Output

['apple', 'banana', 'cherry']

If you modified list x in the above example, the list of the fruits is not modified.

Copy list using slice syntax:

You can create a 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)

Output

old_list:-  ['Python', 'C++', 'C', 'PHP']
new_list:-  ['Python', 'C++', 'C', 'PHP', 'Java']

If you modified the list new_list in the above example, the old_list list was not modified.

Conclusion:

In this tutorial, you have learned about the Python list copy() method to create a copy of the existing list. Using slice syntax and the 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 it with your friends who want to learn Python programming from scratch to advanced.

For More Reference:- Click Here

Previous Article

Related Posts