Python replication and Reference Usage Analysis, python Reference Usage
This example describes how to copy and reference python. Share it with you for your reference. The specific analysis is as follows:
Simple replication is a reference
A = [, 4] B = a # This is reference B. append (2323) print (a, B) # ([1, 23, 4, 2323], [1, 23, 4, 2323])
Use copy. copy for shortest
Import copyc = copy. copy (B) # copy c. append (1) print (B, c) # ([1, 23,4, 2323], [1, 23, 4, 2323, 1]) list1 = [['a'], [1, 2, 4], [23, 'a'] list_copy = copy. copy (list1) # A new object is generated for the shortest copy, however, the attributes and content of the new object are still referenced by the original object. # When the new object is modified as a whole, the list_copy.append ('append') print (list_copy) # [['a'], [1, 2, 4], [23, 'a'], 'append'] print (list1) # [['a'], [1, 2, 4], [23, 'a'] # the original object is modified when the content of the new object is modified, because it still references list_copy [1]. append ('append + ') print (list_copy) # [['a'], [1, 2, 4, 'append +'], [23, 'a'], 'append'] print (list1) # [['a'], [1, 2, 4, 'append + '], [23, 'a']
Copy. deepcopy is used for iterative copying. After that, you can change the attributes of the new object without affecting the original object, but the efficiency and memory usage will decrease.
For list, dict, set, and so on, you can directly use x (object) and copy an object of the corresponding type. This is the simplest and most effective method.
I hope this article will help you with Python programming.