Gotcha Question

John W. Baxter jwbnews at scandaroon.com
Thu Mar 9 13:33:22 EST 2000


In article <8a6ams$fft at autodesk.autodesk.com>, "Akira Kiyomiya" 
<akira.kiyomiya at autodesk.com> wrote:

> >>> L = [1, 2, 3]
> >>> M = ['X', L[:], 'Y']    #embed a copy of L
> >>> L[1] = 0     #only changes L, not M
> >>> L
> [1, 0, 3]
> >>>M
> ['X', [1, 2, 3], 'Y']      #Why??  I know it only changed L, not M.   But
> why is it?

The key is the L[:], which makes a copy of the contents of L, and puts 
that copy into the list assigned to M.  What's in M now has no 
connection to L.  L[:] makes a copy because it is a slice of L...it is a 
slice which contains all of the elements of L, but it isn't L.

  --John
(Note...I have dual motives in posting this:  firstly I'm trying to help 
in my usual fumbling way; secondly I am testing our news provider, which 
may not be happy today.)

-- 
John W. Baxter   Port Ludlow, WA USA  jwbnews at scandaroon.com



More information about the Python-list mailing list