Difference between using deepcopy and substring operation
I am using Python 2.7
I have a list lst = ['a','b','c']
If I need a copy if this list, I used to do lst_cpy = lst[:]
.
I came across a function deepcopy
in the package copy
which enables me to achieve the same.
import copy
lst_cpy_2 = copy.deepcopy(lst)
Can I use these two methods interchangeably or is there开发者_高级运维 any difference between the two?
Thanks.
In the case of a simple list, they are the same. If your list had other structures within it, for example, elements which were lists or dictionaries, they would be different.
L[:]
makes a new list, and each element in the new list is a new reference to the values in the old list. If one of those values is mutable, changes to it will be seen in the new list. copy.deepcopy()
makes a new list, and each element is itself a deep copy of the values in the old list. So nested data structures are copied at every level.
Since there is no way/need to deepcopy a string, slicing this particular list has the same effect. But normally [:]
performs a shallow copy of a sequence.
I believe the difference is when one of the items in your list is a list, dict, or other mutable object. With a normal copy, the object is shared between copies:
>>> l = ['a','b',[1,2]]
>>> l2 = l[:]
>>> l2[2].append('c')
>>> l
['a', 'b', [1, 2, 'c']]
but with deepcopy()
, the object is copied as well:
>>> l2 = copy.deepcopy(l)
>>> l2[2].append('d')
>>> l
['a', 'b', [1, 2, 'c']]
>>> l2
['a', 'b', [1, 2, 'c', 'd']]
精彩评论