Python USES the copy module to implement the of list copy of the list

  • 2020-05-09 18:49:03
  • OfStack

A reference is the address where the value is saved as an object. In the Python language, a variable holds a value that is referenced except for a value for the base type, so you need to be careful with them. Here's an example:

Problem description: given 1 list, survival into a new list, the list element is a copy of the original list


a=[1,2]
b=a

Instead of actually generating a new list, b is still pointing to the same object that a is pointing to. Thus, if an element of a or b is modified, the values of a and b change simultaneously.

The solution is as follows:


a=[1,2]
b=a[:]

This modification of a has no effect on b. Modification of b has no effect on a.

But this only works for simple lists, where the elements in a list are of basic types, and it doesn't work if the list elements still have a list. The reason for this is that, like a[:], it simply generates a new list from the values of the column table elements. If the list element is also a new list, such as: a=[1,[2]], then the copy processing of the element [2] only copies the reference to [2], but does not generate a new list copy of [2]. To prove this point, the test steps are as follows:


>>> a=[1,[2]]
>>> b=a[:]
>>> b
[1, [2]]
>>> a[1].append(3)
>>> a
[1, [2, 3]]
>>> b
[1, [2, 3]]

It can be seen that the modification to a affects b. If you solve this 1 problem, you can use the deepcopy function in the copy module. Modify the test as follows:

>>> import copy
>>> a=[1,[2]]
>>> b=copy.deepcopy(a)
>>> b
[1, [2]]
>>> a[1].append(3)
>>> a
[1, [2, 3]]
>>> b
[1, [2]]

Sometimes it's important to know this point, because maybe you do need a new list and you want to manipulate the new list without affecting the original list.


Related articles: