Function Instance Usage in python copy Module

  • 2021-11-29 08:01:39
  • OfStack

1. The copy. copy () function can be used to copy variable values such as lists or dictionaries. The copied list and the original list are two independent lists.


import copy
origin = [1,2,3]
new = copy.copy(origin)
new[0] = 0
print("origin = ",origin)
print("new = ",new)

2. If there is a list in the list to be copied, use the deepcopy () function to copy it completely.


import copy
origin =[[1,2,3],['a','b','c']]
new = copy.deepcopy(origin) # Use depth copy
new[0][0] = 0
print("origin = ",origin)
print("new = ",new)

Knowledge point supplement:

Introduction of copy Module

copy Module

The copy module is used for copying objects. The copy module is very simple, with only two api. They are copy. copy (x) and copy. deepcopy (x). These two functions return shallow copy and deep copy of parameter x, respectively. This module provides only two main methods:

copy. copy: Shallow replication (Shallow copy) copy. deepcopy: Deep replication (Deep copy)

Related articles: