Split a list into two parts based on a filter?

Roel Schroeven roel at roelschroeven.net
Mon Jun 10 18:50:30 EDT 2013


Roy Smith schreef:
> 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?

You could do something like:

new_songs, old_songs = [], []
[(new_songs if s.is_new() else old_songs).append(s) for s in songs]

But I'm not sure that that's any better than the long version.

-- 
"People almost invariably arrive at their beliefs not on the basis of
proof but on the basis of what they find attractive."
         -- Pascal Blaise

roel at roelschroeven.net




More information about the Python-list mailing list