Skip to content Skip to sidebar Skip to footer

Python List.copy Shallow Vs Deep Copy

Maybe I don't understand the definition of shallow copy... but i'm very confused: from the docs: Where 's' is a list (but same question applies to dictionaries respectively). 's.c

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Python List.copy Shallow Vs Deep Copy"