How to make a copy of the Python list

Copy a Python list with ease: use list.copy() or list[:] to make a shallow copy, or copy.deepcopy() for a deep copy.

A copy of a Python list can be created with the list.copy() method. This method is used to create a shallow copy of a list, which contains the same elements as the original list. The new list is a separate object from the original list and changes made to the new list will not affect the original list.

To create a copy of a Python list, you can use the following code:

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

print(original_list)
print(copied_list)

The output of this code will be the following:

[1,2,3,4,5]
[1,2,3,4,5]

As you can see, the two lists contain the same elements. The copy() method creates a shallow copy of the list, so changes made to the copied list will not affect the original list.

What is a shallow copy?

A shallow copy is a copy of an object which contains the same elements as the original object. However, a shallow copy does not create a separate object for each element in the original object. Instead, a shallow copy creates a single new object containing references to the elements of the original object.

For example, if the original list contains a list of numbers, the shallow copy will contain a reference to the original list of numbers. If the original list contains a list of strings, the shallow copy will contain a reference to the original list of strings. Changes made to the elements in the shallow copy will affect the elements in the original list.

Answers (0)