Python List copy() Method



The Python list copy() method is used to create a shallow copy of a list. A shallow copy means that a new list object is created, but the elements within the new list are references to the same objects as the original list.

Therefore, changes made to the elements of the original list will also affect the elements of the copied list, and vice versa. However, the list objects themselves are independent.

Syntax

Following is the basic syntax of the Python List copy() method −

list.copy()

Parameter

This method does not accept any parameters.

Return Value

The method returns a new list that contains the same elements as the original list.

Example

In the following example, we are creating a shallow copy of the list "my_list" and assigning it to "copied_list". Both lists contain the same elements −

my_list = [1, 2, 3, 4, 5]
copied_list = my_list.copy()
print("The list obtained is:",copied_list)   

Output

The output obtained is as follows −

The list obtained is: [1, 2, 3, 4, 5]

Example

Here, we demonstrate that modifying the original list "my_list" after creating a copy "copied_list" does not affect the copied list −

my_list = [1, 2, 3, 4, 5]
copied_list = my_list.copy()
my_list.append(6)
print("The list obtained is:",copied_list)    

Output

Following is the output of the above code −

The list obtained is: [1, 2, 3, 4, 5]

Example

In this example, we create a shallow copy of a list of lists. The copied list contains references to the same inner lists as the original list −

list_of_lists = [[1, 2], [3, 4], [5, 6]]
copied_list = list_of_lists.copy()
print("The list obtained is:",copied_list)     

Output

The result produced is as shown below −

The list obtained is: [[1, 2], [3, 4], [5, 6]]

Example

Now, we demonstrate that copying an empty list results in another empty list −

empty_list = []
copied_list = empty_list.copy()
print("The list obtained is:",copied_list)  

Output

We get the output as shown below −

The list obtained is: []
python_list_methods.htm
Advertisements