Lists into lists

Ignacio Vazquez-Abrams ignacio at openservices.net
Mon Aug 20 16:52:27 CEST 2001


On Mon, 20 Aug 2001, Jeff Cohen wrote:

> I'm just learning python, so sorry if this is obvious but I didn't see it in
> the book or a few tutorials I found.
>
> I want to insert a copy of a list into a list like so:
>
> >>x=[1,2,3]
> >>y=[4,5,6]
> >> Magic step goes here
> >>x
> [[4,5,6],1,2,3]
>
> Now, I did this with
>
> >>x.insert(0,y)
>
> However, when I manipulate y, I end up changing x as well.
>
> With
>
> >>x[:0]=y
> >>x
> [4,5,6,1,2,3]
>
> Which isn't exactly it either.
>
> Any help there?

Inserting y into x just inserts a reference to y into x. You need to insert
y[:] into x, which then makes a copy of y.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list