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.