0

Consider the following

from copy import deepcopy
c = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
dc = c.copy()
d = deepcopy(dc)
d['username'] = 'mln'
d['machines'].remove('bar')
print d
print c 

the result is as follows:

{'username': 'mln', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'bar', 'baz']}

but when using shallow copy, things will be different.

a = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
b = a.copy()
b['username']='mln'
b['machines'].remove('bar')
print b
print a

the result is as follows:

{'username': 'mln', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'baz']}
  1. So for the key "machines" in dict d, when using deep copy, Python will create a new list object which is different to the list object in dict c.

  2. But when using shallow copy, there's only one list object and both dictionaries point at it.

  3. What's more, when I use shallow copy, for objects like tuple and str, it creates a new object.

  4. But for dictionary and list,it just adds another reference. When using deep copy, both create a new object.

Am I right?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
RuiCao
  • 3
  • 2

1 Answers1

0

From the docs:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

1.A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

2.A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

so..

  1. yes
  2. yes
  3. No When you use shallow copy,for string and tuple it does not create a new object. ex :
>>> s1 = "string1"
>>> s2 = copy.copy(s1)
>>> id(s2) == id(s1)
True
>>> id(s2[0]) == id(s1[0])
True

both are pointing to same object..!

  1. Yes,if we use deep copy,new objects are created for dictionaries and lists as they are compound objects.

check this link for more info: What exactly is the difference between shallow copy, deepcopy and normal assignment operation?

Community
  • 1
  • 1
ymdatta
  • 80
  • 7
  • 1
    in addition to what @valacmur says, note that in the line `b['username']='mln'` you create a new reference yourself, this is why it is not the same after the print – Elisha Mar 26 '17 at 12:11