Efficient way to break up a list into two pieces

Carl Banks pavlovevidence at gmail.com
Sun Feb 21 07:38:53 CET 2010

On Feb 20, 4:55 pm, marwie <mar... at gmx.de> wrote:
> Hello,
> I recently read about augmented assignments and that (with l1, l2
> being lists)
>     l1.extend(l2)
> is more efficient than
>     l1 = l1 + l2
> because unnecessary copy operations can be avoided. Now my question is
> if there's a similar thing for breaking a list into two parts. Let's
> say I want to remove from l1 everything from and including position 10
> and store it in l2. Then I can write
>     l2 = l1[10:]
>     del l1[10:]
> But since I'm assigning a slice the elements will be copied.

That's about the best you can do with Python lists.

> Basically, I'm looking for something like l1.pop(10,len(l1)) which
> returns and removes a whole chunk of data. Is there such a thing (and
> if not, why not?)

Numpy arrays can share underlying data like that when you take
slices.  For instance, this probably works the way you want:

a = numpy.array([1,2,3,4,5,6])
b = a[:3]
c = a[3:]

None of the actual data was copied here.

Carl Banks

More information about the Python-list mailing list