emanuele
emanuele

Reputation: 2589

Is this y = y + [] a deep copy or a shallow copy?

Let this code

x = [1, 2, 3, 4, 5, 6]
y = x
y = y + []

Is y a deep or shallow copy of x?

Upvotes: 1

Views: 461

Answers (3)

timgeb
timgeb

Reputation: 78740

I would not call what you are doing a copy-operation at all. You are building a new list y + [] and assign it to the name y.

The + operator does not copy anything when using it on lists, so the items in y and the items in x will be the same (as in literally the same objects in memory).

This holds true whether or not the contents of any of the lists are mutable, mutability should not be brought into this discussion.

>>> x = [1,2,3,4,5,6]
>>> y = x
>>> y = y +[]
>>> all(a is b for a,b in zip(y,x))
True    
>>> x = [[1], [2]]
>>> y = x
>>> y = y + []
>>> all(a is b for a,b in zip(y,x))
True

The only thing to watch out for when dealing with mutable elements is that changes to any of the mutable elements will be seen across all containers which hold a reference to them.

>>> y[0][0] = 3
>>> x
[[3], [2]]

Upvotes: 1

Blckknght
Blckknght

Reputation: 104732

It's a shallow copy, but in this case there's no difference between a shallow and a deep copy, since the integers inside the list are immutable. In fact, they're all small enough that the standard Python interpreter (cpython) will cache them (every 1 is the same object), so a deep copy would have the exact same contents as a shallow copy (the contents will be the same by identity, not just value).

Upvotes: 7

Kijewski
Kijewski

Reputation: 26032

This line performs a shallow copy of the list y:

y = y + []

Why do you think it would be a deep copy?

But since ints are atomic and immutable, the term "copy" does not really apply. For your example it simply does not matter. If y contained some objects, yeah, then it's a shallow copy, because the contained elements are not copied.

Python's man page for the module "copy" contains all the information you need to understand the difference between a shallow and a deep copy: https://docs.python.org/3/library/copy.html

Upvotes: 3

Related Questions