Split a list into two parts based on a filter?

Roy Smith roy at panix.com
Mon Jun 10 16:34:54 EDT 2013


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?



More information about the Python-list mailing list