2

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

Azat Ibrakov
11.1k9 gold badges43 silver badges58 bronze badges
asked Jun 1, 2013 at 11:04
1

2 Answers 2

5
>>> 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]]
answered Jun 1, 2013 at 11:10
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.

answered Jun 1, 2013 at 11:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.