Use the copy module in Python to implement list copy and pythoncopy
Reference refers to the address where the stored value is the object. In Python, values stored in a variable are referenced in addition to values of the basic type. Therefore, you must be careful when using them. The following is an example:
Problem description: A list is known to survive into a new list. The list element is the copy of the original list.
Copy codeThe Code is as follows:
A = [1, 2]
B =
In fact, this method does not actually generate a new list, and B points to the object that a points. In this way, if the elements a or B are modified, the values of a and B change at the same time.
Solution:
Copy codeThe Code is as follows:
A = [1, 2]
B = a [:]
In this way, modifying a has no effect on B. Modifying B has no effect on.
However, this method is only applicable to simple lists, that is, all elements in the list are of the basic type. If the list element still exists, this method is not applicable. This is because, for example, a [:], only generates a new list of column table element values. If the list element is also a list, for example, a = [1, [2], then this replication only copies the reference of [2] for element [2], but does not generate a new list copy of [2. To prove this, the test procedure is as follows:
Copy codeThe Code is as follows:
>>> A = [1, [2]
>>> B = a [:]
>>> B
[1, [2]
>>> A [1]. append (3)
>>>
[1, [2, 3]
>>> B
[1, [2, 3]
It can be seen that the modification to a affects B. To solve this problem, you can use the deepcopy function in the copy module. The modification test is as follows:
Copy codeThe Code is as follows:
>>> Import copy
>>> A = [1, [2]
>>> B = copy. deepcopy ()
>>> B
[1, [2]
>>> A [1]. append (3)
>>>
[1, [2, 3]
>>> B
[1, [2]
Sometimes it is very important to know this, because you may need a new list and operate it without affecting the original list.