[Tutor] Copy and Deepcopy (List aliasing)

Wesley Chun wesc@deirdre.org
Mon, 16 Jul 2001 11:53:24 -0700 (PDT)


On Sat, 14 Jul 2001, Christopher Smith wrote:
>
> I've run into a perplexing issue and would like to understand the issues
> better:
>
> I create a list
> 	>>> l=[0,0]
> and make a copy with a new id (by using l+[] on the rhs instead of just l)
> 	>>> n=l+[]
> so that changes to one
> 	>>> n[0]=42
> don't affect the other
> 	>>> n
> 	[42, 0]
> 	>>> l
> 	[0, 0]
>
> I try it with a *nested* list
> 	>>> l=[[0,0],[0,0]]
> 	>>> n=l+[]
> 	>>> n[0][0]=42
> and find that even though the n and l are not the same
> 	>>> id(n)
> 	59984352
> 	>>> id(l)
> 	60175248
> n[0] and l[0] *are the same*
> 	>>> id(n[0])
> 	59985088
> 	>>> id(l[0])
> 	59985088
> so that changes to one *do affect* the other
> 	>>> l[0]
> 	[42, 0]
> 	>>> n[0]
> 	[42, 0]
>
> 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.


christopher,

you know, i discovered *exactly* the same thing as you!!  danny's
"diagrams" are definitely helpful too, but let me try to summarize what's
going on.

you made a copy of an object, a list, so now you have 2 different objects.
by default, this copy is a shallow copy, meaning that only the container
object is copied -- not the stuff *inside* it.  those things are just
references to the exact same objects.

a deep copy not only copies the container object, but also makes copies of
its contents too!

more details, analysis, including an example which looks strangely like a
"shallow copy" of yours can be found in Section 6.19 in Core Python
Programming on pp.  201-203.

hope this helps!

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Silicon Valley-SF Bay Area Python users group:  http://baypiggies.org

"Core Python Programming", Prentice Hall PTR, December 2000
    http://starship.python.net/crew/wesc/cpp/

wesley.j.chun :: wesc@baypiggies.org
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/