python list.copy shallow vs deep copy
This question already has an answer here:
You've simply misunderstood what "shallow" and "deep" mean in this context.
A shallow copy is a copy of the top level of elements only. If any of those elements are themselves lists, the copies will still refer to the original lists. This is what both l1[:]
and l1.copy()
do.
A deep copy is a copy at all levels. If any of the elements are lists, they will also be deep copied. No references will be shared. This is what copy.deepcopy()
does.
A shallow copy means that the new list holds references to the same object that the old list has.
For example:
foo = [1, 2, []]
bar = foo.copy()
bar[-1].append(3)
print(foo)
We'll see that mutations of objects in bar
also "pollute" foo
.
If we re-do this example using a deep copy, it's a different story:
import copy
foo = [1, 2, []]
bar = copy.deepcopy(foo)
bar[-1].append(3)
print(foo)
This is because the deep copy creates a new (deep copy) of the list instead of just copying over a reference to the old list.
链接地址: http://www.djcxy.com/p/79356.html