How to Copy a List in Python? | Python Tutorial
Five Different Techniques with Examples
--
As Python programmers several times, we need to copy a list to another list.
Most newbies try to use a “=”(assignment operator) to do this. But there are certain restrictions when you try to use the “=” operator.
With “=” (assignment operator) when you try to modify the new List, in that case, the old List will be modified as well.
Python provides us with a method called copy()
that returns a shallow copy of the list.
Let’s discuss everything in detail.
1. Use Python List copy() to copy a list
The Python copy()
method is used to copy a list.
This method returns the copied list.
You don’t need to provide any parameters while using this method.
The copy()
method returns the shallow copy of the list.
Before we dive right into how we copy a list in python, let’s first see the copy()
method syntax.
copy() method syntax
new_list = list.copy()
The copy()
method does not take any type of parameters.
Examples
my_list = [1,2,3,4]
new_list = my_list.copy()
print('Copied list: ' , new_list)
#Return
Copied list: [1, 2, 3, 4]
In the example above, we use the copy()
method to create a new list using the old list.
However, we don’t see if the list returns a shallow copy or not.
Let’s first understand what is meant by shallow copy.
Shallow copy
Before explaining shallow copy, you should remember that the concept of shallow and deep copy is relevant only to compound objects.
Compound objects mainly include nested structures such as a list of lists or a dictionary of sets.
With shallow copies, duplication is minimal.
A shallow copy of a list is a copy of the list structure and not the elements.