To deep copy a list in Python, you can use the `deepcopy` function from the `copy` module. This function creates a new copy of the list and all its nested elements, ensuring that changes made to the copied list do not affect the original list or its elements.
In this example,
import copy
original_list = [[1, 2], [3, 4]]
deep_copied_list = copy.deepcopy(original_list)
print('Original List:', original_list)
print('Deep Copied List:', deep_copied_list)
Original List: [[1, 2], [3, 4]] Deep Copied List: [[1, 2], [3, 4]]
In this example,
original_list = [[1, 2], [3, 4]]
deep_copied_list = [x[:] for x in original_list]
print('Original List:', original_list)
print('Deep Copied List:', deep_copied_list)
Original List: [[1, 2], [3, 4]] Deep Copied List: [[1, 2], [3, 4]]
In this tutorial, we learned How to deep Copy a List in Python language with well detailed examples.