The copy Method in Python: Copying a List

The copy method creates a copy of a list. This method works like the expression my_list[:].

copy()

my_list = [1, 2, 3]
my_list_copy = my_list.copy()  # [1, 2, 3]
my_list_copy_2 = my_list[:]  # [1, 2, 3]

This is a shallow copy, so it doesn’t recursively copy nested elements. Changes in nested lists affect both the original and its copy:

second_list = [[1, 2], [3, 4]]
second_list_copy = second_list.copy()  # [[1, 2], [3, 4]]
second_list[0].append(5)  # second_list = [[1, 2, 5], [3, 4]]
print(second_list_copy)  # [[1, 2, 5], [3, 4]]

To create a deep copy, use the copy module.