[Tutor] Copy and Deepcopy (List aliasing)

Christopher Smith csmith@blakeschool.org
Sun, 15 Jul 2001 15:25:19 -0500


>From: sill@optonline.net
>
>> I know that using n=deepcopy(l) fixes the problem, but can anyone 
>> help me understand what is going on?  Is there any other simple  
>> way to make a copy of l without using deepcopy?  The "=" is a 
>> little more tricky than I have suspected.
>
>Umm.. there's newlst = lst[:]

This provides a shallow copy:

>>> a=[1,2]
>>> b=[2,3,4]
>>> l=[a,b]
>>> l
[[1, 2], [2, 3, 4]]
>>> n=l[:]
>>> n
[[1, 2], [2, 3, 4]]
>>> n[0][0]=42
>>> n
[[42, 2], [2, 3, 4]]
>>> l
[[42, 2], [2, 3, 4]]

Note that l caught the change, too.

/c