python copy and reference usage analysis

  • 2020-05-07 19:55:27
  • OfStack

This article illustrates the use of python replication and references. Share with you for your reference. Specific analysis is as follows:

Simple replication is a reference


a=[1,23,4]
b=a # This is a quote 
b.append(2323)
print(a,b) #([1, 23, 4, 2323], [1, 23, 4, 2323])

Use copy.copy for shallow copy


import copy
c=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)
# Shallow copy, made 1 The properties and contents of the new object are still references to the original object 

# When you modify a new object as a whole, you modify itself 
list_copy.append('append')
print(list_copy)#[['a'], [1, 2, 4], [23, 'a'], 'append']
print(list1)#[['a'], [1, 2, 4], [23, 'a']]

# When the contents of a new object are modified, the original object is modified because it is still a reference 
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']]

USES copy.deepcopy to copy iteratively, and then you can change the properties of the new object without affecting the original object, except that the efficiency decreases and the memory footprint increases.

for list, dict, set can directly use x(object), object for the corresponding type, copy, this is the most simple, most direct and effective way.

I hope this article has been helpful to your Python programming.


Related articles: