[Python] Try to use deep copy when performing append operation on the List list


Problem Description

When writing Python code, initialize a variable with the same name and append to a list. When checking, it is found that all elements of the obtained list are variable data just after initialization.


Cause Analysis:

>> The append method is a shallow copy.
In Python, object assignment is actually a reference to an object. When an object is created and then assigned to another variable, Python does not copy the object, but just copies the object. quote.


solution:

Write data using deep copylist.append(copy.deepcopy(item))

Among them, list is the name of the list, and item is the name of the data.


References:
[1] "Python Advanced Series" 29: append shallow copy mechanism-do you really know how to use the append function?

Guess you like

Origin blog.csdn.net/weixin_56917387/article/details/129277391