乐闻世界logo
搜索文章和话题

What is the difference between shallow and deep copying?

1个答案

1

Shallow Copy and Deep Copy are two fundamental techniques for object replication in programming, with notable differences when dealing with complex data structures like lists and dictionaries.

Shallow Copy

A shallow copy creates a new object by copying only the references to the elements of the original object, not the elements themselves. Consequently, if the elements in the original object are mutable, the new object and the original object share references to these mutable elements.

Example: In Python, you can use the copy() function from the copy module to create a shallow copy of an object.

python
import copy original_list = [1, 2, [3, 4]] shallow_copied_list = copy.copy(original_list) shallow_copied_list[2].append(5) print(original_list) # Output: [1, 2, [3, 4, 5]] print(shallow_copied_list) # Output: [1, 2, [3, 4, 5]]

In this example, modifying the sublist in shallow_copied_list also changes the sublist in original_list because they share the same sublist object.

Deep Copy

A deep copy creates a new object and recursively copies all elements of the original object, ensuring that no sub-elements are shared between the new and original objects.

Example: In Python, you can use the deepcopy() function from the copy module to create a deep copy of an object.

python
import copy original_list = [1, 2, [3, 4]] deep_copied_list = copy.deepcopy(original_list) deep_copied_list[2].append(5) print(original_list) # Output: [1, 2, [3, 4]] print(deep_copied_list) # Output: [1, 2, [3, 4, 5]]

In this example, modifying the sublist in deep_copied_list does not affect the sublist in original_list because they are completely independent objects.

Summary

Shallow copy is appropriate when the original object consists solely of immutable elements or when independent copying of sub-objects is unnecessary. Deep copy is suitable for cases requiring complete independence, particularly when the object structure is complex and sub-elements must also be copied independently. The choice between shallow copy and deep copy should be based on specific requirements and the nature of the objects.

2024年10月26日 17:04 回复

你的答案