Split a list into two parts based on a filter?

Phil Connell pconnell at gmail.com
Wed Jun 12 02:32:26 EDT 2013


On 12 Jun 2013 01:36, "Roy Smith" <roy at panix.com> wrote:
>
> In article <mailman.3023.1370964449.3114.python-list at python.org>,
>  Serhiy Storchaka <storchaka at gmail.com> wrote:
>
> > 11.06.13 07:11, Roy Smith написав(ла):
> > > In article <mailman.2992.1370904643.3114.python-list at python.org>,
> > >   Roel Schroeven <roel at roelschroeven.net> wrote:
> > >
> > >> new_songs, old_songs = [], []
> > >> [(new_songs if s.is_new() else old_songs).append(s) for s in songs]
> > >
> > > Thanks kind of neat, thanks.
> > >
> > > I'm trying to figure out what list gets created and discarded.  I
think
> > > it's [None] * len(songs).
> >
> > It is the same as your klunky code, but consumes more memory.
>
> Well, continuing down this somewhat bizarre path:
>
> new_songs, old_songs = [], []
> itertools.takewhile(
>     lambda x: True,
>     (new_songs if s.is_new() else old_songs).append(s) for s in songs)
>     )
>
> I'm not sure I got the syntax exactly right, but the idea is anything
> that will iterate over a generator expression.  That at least gets rid
> of the memory requirement to hold the throw-away list :-)

You could equivalently pass the generator to deque() with maxlen=0 - this
consumes the iterator with constant memory usage.

We are of course firmly in the twilight zone at this point (although this
can be a useful technique in general).

Cheers,
Phil

>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130612/4d76c111/attachment.html>


More information about the Python-list mailing list