Python List copy()
Python List copy() method
Python List copy() method creates a shallow copy of the list, and returns the copied list.
In this tutorial, you will learn the syntax of, and how to use List copy() method, with examples.
Syntax of List copy()
The syntax of List copy() method is
list.copy()
Parameters
copy() method take no parameters.
Return value
copy() method returns a list object.
Examples
1. Copy given list in Python
In the following program, we take a list my_list with values [22, 44, 66]
. We have to make a copy of this list.
Call copy() method on the list my_list, and store the returned value in a variable.
Python Program
my_list = [22, 44, 66]
my_list_copy = my_list.copy()
print(f"Original list : {my_list}")
print(f"Copied list : {my_list_copy}")
Output
Original list : [22, 44, 66]
Copied list : [22, 44, 66]
2. Copy given list of lists in Python - Understanding shallow copy
In the following program, we shall take a list of lists in my_list. We shall use list of integers as elements in the my_list, and then make a copy of this list my_list using List copy() method.
Since copy() method makes a shallow copy, only the references to the inner lists are copied. Therefore, even after making the copy, if we make any changes to the inner lists using their original references, those changes will be reflected in the copied list as well.
Call copy() method on the list my_list, and store the returned value in a variable my_list_copy.
Python Program
list_1 = [22, 44, 66]
list_2 = [11, 33, 55]
# Create a list of lists
my_list = [list_1, list_2]
# Make a copy of this list of lists
my_list_copy = my_list.copy()
# Modify element of the inner list at the original source
list_1[0] = 100
print(f"Original list : {my_list}")
print(f"Copied list : {my_list_copy}")
Output
Original list : [[100, 44, 66], [11, 33, 55]]
Copied list : [[100, 44, 66], [11, 33, 55]]
Please observe that the update made to an item in the list list_1 has affected the original and copied list as well. This is the result of shallow copying. Only the reference to the objects of the top level items in the original list are copied to newly created list. And therefore, any changes made to these items appear in the copied list as well.
Summary
In this tutorial of Python Examples, we learned about List copy() method, how to use copy() method to make a copy of a given list, with syntax and examples.