Copy List

Jason tenax.raccoon at gmail.com
Thu Jul 19 17:54:33 EDT 2007


On Jul 19, 10:21 am, Falcolas <garri... at gmail.com> wrote:
> On Jul 18, 6:56 am, "Rustom Mody" <rustompm... at gmail.com> wrote:
>
> > This is shallow copy
> > If you want deep copy then
> > from copy import deepcopy
>
> What will a "deep copy" of a list give you that using the slice
> notation will not?

With a shallow copy, you end up with a new list object, but the items
contained within the new list object are the same as in the original
list object.  This makes no real difference if the original list only
contains immutable values (such as strings, integers, or floats), but
it can make a big difference if the values are mutable.

>>> originalList = [1, 2, [3, 4]]
>>> shallowCopy = originalList[:]
>>> shallowCopy.append(5)
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4]]
[1, 2, [3, 4], 5]
>>> originalList[2].append(100) # Mutate the list inside this list
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4, 100]]
[1, 2, [3, 4, 100], 5]
>>>

As you can see in the above code snipped, the original list contains a
list at index 2.  The slice copy is a different list, so appending a 5
to it doesn't modify the original list.  However, the result of
appending 100 to the object at index 2 can be seen in both lists.  A
deep copy creates a new object for ever item in the list, and all
items in those items, and so forth, so the lists guaranteed to be
truly disconnected:

>>> from copy import deepcopy
>>> originalList = [1, [2, [3, 4]]]
>>> fullCopy = deepcopy(originalList)
>>> originalList[1][1].append(100)
>>> print originalList, '\n', fullCopy
[1, [2, [3, 4, 100]]]
[1, [2, [3, 4]]]
>>>


  --Jason




More information about the Python-list mailing list