Why deepcopy of list of integers returns the same integers in memory?

Gerald Lee picture Gerald Lee · Jul 25, 2015 · Viewed 11.1k times · Source

I understand the differences between shallow copy and deep copy as I have learnt in class. However the following doesn't make sense

import copy

a = [1, 2, 3, 4, 5] 

b = copy.deepcopy(a)

print(a is b)
print(a[0] is b[0])
----------------------------
~Output~
>False
>True
----------------------------

Shouldn't print(a[0] is b[0]) evaluate to False as the objects and their constituent elements are being recreated at a different memory location in a deep copy? I was just testing this out as we had discussed this in class yet it doesn't seem to work.

Answer

Olivier Melançon picture Olivier Melançon · Jan 6, 2018

It was suggested in another answer that this may be due to the fact Python has interned objects for small integers. While this statement is correct, it is not what causes that behaviour.

Let's have a look at what happens when we use bigger integers.

> from copy import deepcopy
> x = 1000
> x is deepcopy(x)
True

If we dig down in the copy module we find out that calling deepcopy with an atomic value defers the call to the function _deepcopy_atomic.

def _deepcopy_atomic(x, memo):
    return x

So what is actually happening is that deepcopy will not copy an atomic value, but only return it.

By example this is the case for int, float, str, function and more.