What is difference between copy.copy and copy.deepcopy functions in python?
>>> copy.deepcopy(li)
[1, 2, 3, 4]
>>> copy.copy(li)
[1, 2, 3, 4]
both does the same thing , can anyone tell what these functions does specifically
-
1docs.python.org/2/library/copy.htmlAshwini Chaudhary– Ashwini Chaudhary06/01/2013 11:29:57Commented Jun 1, 2013 at 11:29
2 Answers 2
>>> import copy
>>> L = [[1,2,3]]
>>> A = copy.copy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3, 4]]
>>> L = [[1,2,3]]
>>> A = copy.deepcopy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3]]
copy.copy
performs a shallow copy as opposed to copy.deepcopy
which performs a deep copy.
When considering:
li = [1, 2, 3, 4]
you will not notice any difference, because you are copying immutable objects, however consider:
>>> import copy
>>> x = copy.copy(li)
>>> x
[[1, 2], [3, 4]]
>>> x[0][0] = 9
>>> li
[[9, 2], [3, 4]]
Since a shallow copy only makes copies of each reference in the list, manipulating these copied references will still affect the original list.
However the following code:
>>> x.append(1)
will have no effect on the original list.