In Python, one of the most straightforward ways to create a shallow copy of a list is by using the list.copy()
method. This operation is fundamental in data manipulation as it prevents the alteration of the original data while performing various operations on the copy.
Before we delve further, let's understand what a shallow copy is. In Python, a shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In other words, a shallow copy is a bit-by-bit copy of an object’s reference. For mutable elements, changes to the original list will affect its copy, but this is not the case for immutable elements.
The list.copy()
method returns a shallow copy of the list. Unlike assignment, where both lists refer to the same objects, the list.copy()
method actually creates a new list containing the same elements as the original. This method is useful when you want to make changes to a list, but you don't want those changes to affect the original list.
Let's illustrate this with an example:
original_list = [1, 2, 3, 4, 5]
copied_list = original_list.copy()
# Now let's change a value in the copied list.
copied_list[0] = 10
print(copied_list) # Output: [10, 2, 3, 4, 5]
print(original_list) # Output: [1, 2, 3, 4, 5]
As you can see, the original_list
remains unchanged even though we altered the copied_list
.
However, do note that list.copy()
creates a shallow copy. If the list contains mutable elements like another list, any changes to the mutable elements in the copied list will reflect on the original list.
original_list = [[1, 2, 3], 4, 5]
copied_list = original_list.copy()
copied_list[0][0] = 10
print(copied_list) # Output: [[10, 2, 3], 4, 5]
print(original_list) # Output: [[10, 2, 3], 4, 5]
Here, changing the sub-list in copied_list
also changes the original_list
because only a shallow copy was made.
If you want to copy the list so that modifications to the copied list do not affect the original list, Python provides a deepcopy()
method through its copy
module. This method creates a deep copy, meaning any changes made to a copy of the list will not affect the original list, even if the list elements are mutable.
In a nutshell, the list.copy()
method is a convenient method when you want to manipulate a list without changing the original one. However, it only creates a shallow copy, so be cautious when your list contains mutable elements.