How to Use the Python List copy() Method

09/12/2021

Contents

In this article, you will learn how to use the Python list copy() method.

Python List copy() Method

The copy() method in Python is used to create a shallow copy of a list. A shallow copy means that a new list is created, but the elements in the new list are still references to the elements in the original list, rather than being completely separate and independent objects.

Here’s how you can use the copy() method in Python:

original_list = [1, 2, 3, 4, 5]
new_list = original_list.copy()

print("Original list:", original_list)
print("New list:", new_list)

# Output
# Original list: [1, 2, 3, 4, 5]
# New list: [1, 2, 3, 4, 5]

As you can see, the new_list is a copy of the original_list. If you modify the new_list, it will not affect the original_list:

new_list[0] = 100

print("Original list:", original_list)
print("New list:", new_list)

# Output
# Original list: [1, 2, 3, 4, 5]
# New list: [100, 2, 3, 4, 5]

If you need a deep copy of a list, where the elements in the new list are completely separate and independent objects, you can use the copy module in Python:

import copy

original_list = [1, 2, 3, 4, 5]
new_list = copy.deepcopy(original_list)

print("Original list:", original_list)
print("New list:", new_list)

# Output
# Original list: [1, 2, 3, 4, 5]
# New list: [1, 2, 3, 4, 5]
 

Let’s look at some examples to understand the difference between a shallow copy and a deep copy.

Consider a nested list:

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

If you make a shallow copy of this list using the copy() method:

new_list = original_list.copy()

Both original_list and new_list would contain references to the same sublists:

print(original_list)
# [[1, 2, 3], [4, 5, 6]]

print(new_list)
# [[1, 2, 3], [4, 5, 6]]

print(original_list[0] is new_list[0])
# True

This means that if you modify the sublists in the new_list, the sublists in the original_list would also be modified:

new_list[0][0] = 100

print(original_list)
# [[100, 2, 3], [4, 5, 6]]

print(new_list)
# [[100, 2, 3], [4, 5, 6]]

If you want to create a completely independent copy of the nested list, you can use the deepcopy() method from the copy module:

import copy

new_list = copy.deepcopy(original_list)

Now, original_list and new_list would contain completely independent sublists:

print(original_list)
# [[1, 2, 3], [4, 5, 6]]

print(new_list)
# [[1, 2, 3], [4, 5, 6]]

print(original_list[0] is new_list[0])
# False

So, if you modify the sublists in the new_list, the sublists in the original_list would not be affected:

new_list[0][0] = 100

print(original_list)
# [[1, 2, 3], [4, 5, 6]]

print(new_list)
# [[100, 2, 3], [4, 5, 6]]