Split a list into two parts based on a filter?

Chris Rebert clp2 at rebertia.com
Mon Jun 10 19:03:42 EDT 2013


On Mon, Jun 10, 2013 at 1:34 PM, Roy Smith <roy at panix.com> wrote:
> I have a list, songs, which I want to divide into two groups.
> Essentially, I want:
>
> new_songs = [s for s in songs if s.is_new()]
> old_songs = [s for s in songs if not s.is_new()]
>
> but I don't want to make two passes over the list.  I could do:
>
> new_songs = []
> old_songs = []
> for s in songs:
>     if s.is_new():
>         new_songs.append(s)
>     else:
>         old_songs.append(s)
>
> Which works, but is klunky compared to the two-liner above.  This
> seems like a common enough thing that I was expecting to find
> something in itertools which did this.  I'm thinking something along
> the lines of:
>
> matches, non_matches = isplit(lambda s: s.is_new, songs)
>
> Does such a thing exist?

itertools.groupby() is kinda similar, but unfortunately doesn't fit
the bill due to its sorting requirement.
There is regrettably no itertools.partition(). And given how dead-set
Raymond seems to be against adding things to the itertools module,
there will likely never be.
Maybe more-itertools (https://pypi.python.org/pypi/more-itertools )
would accept a patch?

Cheers,
Chris



More information about the Python-list mailing list