Gotcha Question

Hans Nowak hnowak at cuci.nl
Wed Mar 8 16:34:57 EST 2000


On 8 Mar 00, at 11:46, Akira Kiyomiya 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?

Well, you already said it yourself... this statement

    M = ['X', L[:], 'Y']    #embed a copy of L

indeed embeds a *copy* of L. This copy is unrelated to the original list. 
If you do something like

    L = [1, 2, 3]
    M = L[:]

then you will notice that these two lists are unrelated; changes in one of 
them do not affect the other. This is different from

    N = L

where N is merely a reference to L. Or in other words, N and L are 
different names for the same list.

> 2.
> >>>L = [4, 5, 6]
> >>> X = L * 4
> >>>Y = [L] * 4
> >>> X
> [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]      # yeah, it is easy
> >>>Y
> [[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]   # yeah, it is easy
> 
> >>> L[1] = 0;   # impacts y but not x
> >>> X
> [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]      # why?
> >>>Y
> [[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]   # yeah, I understand this.

    X = L * 4

creates a new list, consisting of the elements of a list, in this case L, 
and this 4 times. Again, this list is independent from the original list L, 
much like the [:] was.

    Y = [L] * 4

does essentially the same... it takes a list, 4 times. However, this list 
happens not to be L, but [L], a list containing a reference to L. You end 
up with a list with 4 times this reference.

HTH,

--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://www.hvision.nl/~ivnowa/newsite/
Python questions? See http://tor.dhs.org/~zephyrfalcon/snippets
You call me a masterless man. You are wrong. I am my own master.




More information about the Python-list mailing list