0

whats the difference between shallow and deep copying ? i read on python docs (http://docs.python.org/2/library/copy.html). it basically said shallow copying makes references while deep copying actually copies. so i created a list through shallow copying and changed its values.but the changes werent reflected in the original list.how is that so if shallow copying works on references? (just for the record ,I am using python 2.7.5)

>>>li = [1,2,3,4]
>>> x = copy(li)
>>> x
[1, 2, 3, 4]
>>> x[0]=9
>>> x
[9, 2, 3, 4]
>>> li
[1, 2, 3, 4]
  • You can find detiled explanation here http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy – Vb407 Dec 20 '13 at 09:28

2 Answers2

0

copy creates a copy of the list but does not copy its elements. New list contains references to the original list's elements.

deepcopy creates a separate copy of everything.

See:

import copy

li = [[1], 2]
x = copy.copy(li)
x[0][0] = 2
x[1] = 3
print li
print x
Tomek Szpakowicz
  • 14,063
  • 3
  • 33
  • 55
0

The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the portion of this article about difference between Shallow and Deep copy constructors.

royal52
  • 29
  • 4