Efficient way to break up a list into two pieces
Shashwat Anand
anand.shashwat at gmail.com
Sat Feb 20 20:12:01 EST 2010
You can always implement your own data-structures or simply a function if
you need so. A language consist of building blocks and not buildings.
On Sun, Feb 21, 2010 at 6:36 AM, Jonathan Gardner <
jgardner at jonathangardner.net> wrote:
> On Sat, Feb 20, 2010 at 4:55 PM, marwie <marwie 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.
> > 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?)
> >
>
> The idiom is:
>
> >>> l1, l2 = l1[:10], l1[10:]
>
> Don't know if it's optimized or not. If it's not, it could probably
> be. This is a really common idiom.
>
> --
> Jonathan Gardner
> jgardner at jonathangardner.net
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100221/c156c3b0/attachment-0001.html>
More information about the Python-list
mailing list