Python replication and reference
Simple replication is a reference
a=[1,23,4]b=a # This is a referenceb.append(2323)print(a,b) #([1, 23, 4, 2323], [1, 23, 4, 2323]) |
Use copy. copy for shortest
import copyc=copy.copy(b)# Copyc.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, but the attributes and content of the new object are still references to the original object.# When the new object is modified as a wholelist_copy.append('append')print(list_copy)#[['a'], [1, 2, 4], [23, 'a'], 'append']print(list1)#[['a'], [1, 2, 4], [23, 'a']] # When modifying the content of the new object, the original object is modified because it is still referenced.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.