One, the depth of the copy
If you want to copy a list, you can do this by using the built-in method copy of the list:
1 s = [[1,2],3,4]2 S1 = s.copy () 3 print (s) 4 print (S1)
The copied list S1 is exactly the same as the original list S.
[[1, 2], 3, 4] [[1, 2], 3, 4]
Modification to S1:
1 s = [[1,2],3,4]2 S1 = s.copy () 3 s1[1] = ' Oliver ' 4 s1[0][1] = ' Hello ' 5 print (' list s: ', s) 6 print (' list s1: ', S1)
Output: After modifying element 3 in list S1 to ' Oliver ', the original list is not affected.
When you change the first element in S1 [2] to ' hello ', the original list also changes.
List s: [[1, ' Hello '], 3, 4] list S1: [[1, ' Hello '], ' Oliver ', 4]
The problem is, copy the list by copy method to get the list S1, modify the elements in the S1, the elements in S have not changed, and some have changed. Why is this happening? What is the connection between S and S1? Are the memory spaces completely independent?
As shown, using the built-in copy method of the list points the elements in the new list to the same memory space as the original list. However, if the list is nested within the lists, the list element pointers are nested in the copied list, pointing to the overall address of the nested list in the original list, rather than to the memory address of the element in the nested list.
As a result, s1[0][1] is modified, and the memory space pointed to by the element pointer in the s list also changes.
This is a shallow copy of the list.
If you want the copied list to have a completely separate memory space, you need a new method deep copy to implement:
1 Import copy2 s = [[1,2],3,4]3 s2 = copy.deepcopy (s) 4 s2[0][1] = ' abc ' 5 print (' list s: ', s) 6 print (' List s2: ', s2)
Use the Copy.deepcopy () method to copy the list, modify the elements in the nested list, and the original list is unaffected.
List s: [[1, 2], 3, 4] list s2: [[1, ' abc '], 3, 4]
Summarize
1. A shallow copy can only copy the outermost layer, and the original list and the new list will change when the inner layers are modified.
2. Deep copy refers to the complete cloning of a new copy of the original list.
Python depth copy