How to clone a Python list so there are no unexpected changes after assignment
In Python, you can create a copy of a list by using the built-in copy() method or by using slicing. Here is an example using the copy() method:
import copy # Original list original_list = [1, 2, 3, 4, 5] # Make a copy of the list using copy() cloned_list = copy.copy(original_list) # Modify the original list original_list.append(6) # Print the original and cloned lists print(original_list) # [1, 2, 3, 4, 5, 6] print(cloned_list) # [1, 2, 3, 4, 5]
As you can see, modifying the original list does not affect the cloned list, which remains unchanged. You can also create a copy of a list using slicing:
# Original list original_list = [1, 2, 3, 4, 5] # Make a copy of the list using slicing cloned_list = original_list[:] # Modify the original list original_list.append(6) # Print the original and cloned lists print(original_list) # [1, 2, 3, 4, 5, 6] print(cloned_list) # [1, 2, 3, 4, 5]
This method works because slicing creates a new list object and assigns it to the cloned_list variable.
It's important to note that these methods only create a shallow copy of the list. This means that if the list contains references to other objects (such as nested lists), the copy will still contain references to the same objects as the original list.
To create a deep copy of a list, which creates copies of all objects referenced by the list, you can use the deepcopy() function from the copy module:
import copy # Original list with a nested list original_list = [1, 2, [3, 4]] # Make a deep copy of the list using deepcopy() cloned_list = copy.deepcopy(original_list) # Modify the original list original_list[2].append(5) # Print the original and cloned lists print(original_list) # [1, 2, [3, 4, 5]] print(cloned_list) # [1, 2, [3, 4]]
In this example, the original list has a nested list as one of its elements. Modifying the nested list in the original list does not affect the cloned list, because the deepcopy() function creates a new object for the nested list.