copy of and deepcopy of in Python

  • 2021-12-12 08:56:08
  • OfStack

Directory 1, copy. copy () 2, deepcopy. copy ()

Foreword:

While passing references is often the most convenient way to work with lists and dictionaries, if a function modifies an incoming list or dictionary, it may not want those changes to affect the original list or dictionary. To achieve these one points, Python Provides a file named copy The module of, which contains copy() And deepcopy() Function.

The first function copy.copy() Can be used to copy mutable values such as lists or dictionaries instead of just copying references.

The difference between the two is that copy.copy() Yes, this copies the value of the list or dictionary, but the reference is still the same. And copy.deepcopy() Is to generate a new reference to make the new variable and the copied variable reference different.

Look at the following sample code:

1. copy. copy ()

Sample code:


import copy
spam = ['A','B','C','D',[1,2,3,4]]
cheese = copy.copy(spam)
spam[0] = 42
print(spam)

Run results:

[42,'B','C','D',[1,2,3,4]]

As can be seen from the results, using copy.copy() Function, cheese It's a copy spam List reference to the spam List operation, the cheese The list has an impact. This is also called shallow copy .

2. deepcopy. copy ()

Sample code:


#Python Learning and communication group: 778463939
import copy
spam = ['A','B','C','D',[1,2,3,4]]
cheese = copy.deepcopy(spam)# Different parts 
spam[0] = 42
print(spam)

Run results:

[42,'B','C','D',[1,2,3,4]]

As can be seen from the results, using deepcopy() When, yes spam List operations will not be aligned with cheese The list has an impact because deepcopy() Is to generate 1 new reference, so that spam And cheese

Are two different references, so in the spam The list operation does not affect the cheese list.


Related articles: