An overview of the
In the list copy this problem, seemingly simple copy has a lot of knowledge, especially for the novice, for granted things are not satisfactory, such as list assignment, copy, shallow copy, deep copy and so on the mouth of the noun exactly what is the difference and role?
A list of assignment
Define a new list
l1 = [1.2.3.4.5]
# Assign to L2
l2 = l1
print(l1)
l2[0] = 100
print(l1)
Copy the code
Example results:
[1, 2, 3, 4, 5]
[100, 2, 3, 4, 5]
Copy the code
In Python, a list is a mutable object, and copying a mutable object means that the memory space of the list is similar to that in C, and the pointer points to a new variable name. Instead of immutable objects such as strings, new memory space is created for assignment when copied. L1 and L2 point to the same memory space, so how do we actually copy?
Shallow copy
When the elements in a list are immutable, we can assign the list as follows:
import copy
Define a new list
L0 = [1.2.3.4.5]
print(L0)
print(The '-'*40)
Copy the code
Using the slice
L1 = L0[:]
L1[0] = 100
print(L0)
Copy the code
Using module copy
import copy
L2 = copy.copy(L0)
L2[0] = 100
print(L0)
Copy the code
Use the list ()
L3 = list(L0)
L3[0] = 100
print(L0)
Copy the code
Use the list method extend
L4 = []
L4.extend(L0)
L4[0] = 100
print(L0)
Copy the code
Derive from lists
L5 = [i for i in L0]
L5[0] = 100
print(L0)
Copy the code
The final print result is [1, 2, 3, 4, 5]. We have successfully copied the list, but what if the elements in the list are immutable? If an element in the list is a mutable object, object references will occur during replication, rather than creating a new memory space to reference, for example:
L0 = [1, 2, [3], 4, 5]
print(L0)
L2 = L0[:]
L2[2][0] = 100
print(L0)
Copy the code
Example results:
[1.2[3].4.5]
[1.2[100].4.5]
Copy the code
As can be seen, when the list L0 contains mutable objects, the copied L1 is changed, and the mutable object L0[2] in L0 is also changed when the mutable object element L2[2] is changed. So how to achieve a true full copy?
Deep copy
Use the copy module deepcopy for deepcopy:
import copy
L0 = [1, 2, [3], 4, 5]
print(L0)
L2 = copy.deepcopy(L0)
L2[2][0] = 100
print(L2)
print(L0)
Copy the code
Example results:
[1, 2, [3], 4, 5]Copy the code