Python direct assignment, shallow copy

Introduced a concept, memory address

Direct assignment : Assigning lst1 to lst2 actually assigns the memory address of the stored data specified by lst1 to lst2.
Insert picture description here
Insert picture description here
So after adding an element to lst1, lst2 will also add one, because the memory address has not changed, pointing to the same address.

Shallow copy (copy): create a new object, the memory address changes

Insert picture description here

lst1 = ['王大拿','刘能','赵四']
lst2 = lst1.copy()  #lst2和lst1不是一个对象了,即内存地址不一样
#lst2 = lst1[:] #跟上面操作一样
lst1.append('谢大脚')
print(lst1)
print(lst2)

Insert picture description here

Deep copy:

Insert picture description here

As mentioned above, there is a list in lst1, and then the element of comedy is added to this list. Lst2 itself has shallow copied lst1, and it has also been affected. Apply deep copy at this time

Need to introduce copy library

import copy
lst1 = ['超人','复联','三体',['科幻','恐怖']]
lst2 = copy.deepcopy(lst1)
lst1[3].append('喜剧')
print(lst1)
print(lst2)

Insert picture description here

Published 26 original articles · praised 5 · visits 777

Guess you like

Origin blog.csdn.net/weixin_44730235/article/details/105075940