It is often necessary to copy an object in a program, as the idea should be
It's been copied, but now it's time to change the value of the first element and change it to 5.
I changed the value of the first element of B, but the value of a also changed because the = in Python is a reference. A and B point to the same list, so changing the list will result in the above results.
The workaround is to slice the operation
A = [1, 2, 3]b = a[:]b[0] = 4# [1, 2, 3]# [4, 2, 3]print Aprint b
But when it comes to nesting lists, give it a try.
A = [[4], 4, 5]b = a[:]b[1] = 0 # [[],, 5]# [[], 0, 5]print Aprint b
Well! No problem, try nesting list elements
A = [[4], 4, 5]b = a[:]b[0][0] = AA [[5,2,3],, 5]# [[5,2,3], 4, 5]print aprint BB = a[:]
The value of a is still changed, and slice copy only copies the object and does not copy the child elements.
Copy Module
The copy module is used for copying operations on objects. The module is very simple and provides only two main methods: Copy.copy and Copy.deepcopy, respectively, representing shallow and deep replication. What is shallow copy, what is deep copy, there is a truck-to-truck information on the internet and is not described in detail here. The copy operation is only valid for composite objects. These two methods are described in a simple example.
Shallow copy copies only the object itself, and does not copy the object that the object refers to.
#coding =gbkimport copyl1 = [1, 2, [3, 4]]l2 = copy.copy (L1) print l1print l2l2[2][0] = 50print l1print L2
Results:
[1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]] [1, 2, [50, 4]]
The same code, with a deep copy, results in a different way:
Import COPYL1 = [1, 2, [3, 4]]l2 = copy.deepcopy (L1) print l1print l2l2[2][0] = 50print l1print L2
Results:
[1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [50, 4]]
Change the default behavior of copy
When defining a class, you can change the default behavior of copy by defining the __copy__ and __deepcopy__ methods. The following is a simple example:
Class Copyobj (object): def __repr__ (self): return ' copyobj ' def __copy__ (self): return "Hello" obj = Copyobj () obj1 = copy.copy (obj) print Objprint obj1
Results:
Copyobjhello