3

I was under the impression that deepcopy copied everything recursively down a tree, but I came upon a situation that seemed to go against what I previously believed.

>>> item = "hello"
>>> a["hello"] = item
>>> b = copy.deepcopy(a)
>>> id(a)
31995776
>>> id(b)
32733616             # I expected this
>>> id(a["hello"])
140651836041376
>>> id(b["hello"])
140651836041376      # I did not expect this

The id of a and b are different, which I expected, but the internal item is still the same object. Does deepcopy only copy to a certain depth? Or is this something specific to the way Python stores strings? (I got a similar result with integers as well)

frederj
  • 1,483
  • 9
  • 20
tom
  • 2,335
  • 1
  • 16
  • 30

1 Answers1

5

deepcopy only needs to create copies of mutable objects, like lists and dictionaries. Strings and integers are immutable; they can't be changed in-place, so there's no need to explicitly create a copy, and a reference to the same object is inserted instead.

Here is a quick demo, showing the difference between lists (mutable) and tuples (immutable):

>>> import copy
>>> l = [[1, 2], (3, 4)]
>>> l2 = copy.deepcopy(l)
>>> l2[0] is l[0]
False # created new list
>>> l2[1] is l[1]
True # didn't create new tuple
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437