Home >Backend Development >Python Tutorial >How to Create a True Deep Copy of a List in Python?
How to Create a Deep Copy of a List?
In Python, assigning a list to a new variable using list() does not result in a deep copy. It merely creates a shallow copy, where the inner elements still reference the original list. This can lead to unexpected mutations.
For instance, consider the following code:
E0 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for k in range(3): E0_copy = list(E0) E0_copy[k][k] = 0 print(E0) # [[0, 2, 3], [4, 0, 6], [7, 8, 0]]
In this example, E0_copy is not a deep copy because list() only duplicates the outermost list. The inner elements still point to the same objects in E0. When we modify E0_copy, those changes are also reflected in E0.
To create a genuine deep copy, you should use the copy.deepcopy() function. This function recursively copies all the elements of the list, ensuring that they are completely independent of the original list.
Here's how to write the previous example using a deep copy:
import copy E0 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for k in range(3): E0_copy = copy.deepcopy(E0) E0_copy[k][k] = 0 print(E0) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Notice that after modifying E0_copy, the original list E0 remains unchanged. This is because copy.deepcopy() creates a completely new list that is not tied to the original.
The above is the detailed content of How to Create a True Deep Copy of a List in Python?. For more information, please follow other related articles on the PHP Chinese website!