春江暮客

春江暮客的个人学习分享网站

包含标签 copy 的文章

The difference between shallow copy and deepcopy in Python

The difference between shallow copy and deepcopy in Python

2018年12月29日 | Technology

In Python, copying objects is common, and a lot of “why did both variables change?” bugs come from mixing up three different operations: assignment, shallow copy, and deep copy.

“The difference between shadowcopy and deepcopy in python”

Among assignment (=), shallow copy (copy), and deep copy (deepcopy), the most confusing part is usually not assignment vs. copy, but whether a shallow copy still shares nested mutable objects.

Assignment does not copy an object. It only binds another variable name to the same object. Because of that, changes seen through one variable are still changes to the same underlying object.

A shallow copy duplicates the outer container, but nested mutable objects may still be shared. A deep copy recursively duplicates nested objects too, so it is usually more isolated.

A practical rule of thumb is:

  • Use assignment when you only want another name for the same object.
  • Use shallow copy when copying the outer container is enough.
  • Use deep copy when nested lists or dictionaries also need to be independent.

Below is a practical code example illustrating the differences among the three.

……

阅读全文

友情链接

其它