Splitting lists

Alex Martelli aleax at aleax.it
Thu Feb 27 11:38:54 CET 2003

Ben Wolfson wrote:

> On Thu, 27 Feb 2003 04:10:17 +0100, Ferenczi Viktor wrote:
>> Are there any fast, simple and elegant method to split a list by a filter
>> function?
>> My current solutions with their shortcomings:
>> # Solution 2:
>> tl=[]
>> fl=[]
>> for e in lst:
>>     if fn(e): tl.append(e)
>>     else: fl.append(e)
>> # Relatively slow
> I don't know why you call this one relatively slow; on my system, it's
> faster than the other two--which stands to reason, since the list is only
> traversed once and the function is only called n times.

Yes, and I think it's the most Pythonic approach.  However, it
would not impress people -- it's too clear and understandable,
so everybody can see at once what it does, and nobody will be
oohing and aahing about how "kewl" Python is.

More impressive...:

appenders = tl.append, fl.append
for e in lst: appenders[not fn(e)](e)

now isn't THAT more like it...?


More information about the Python-list mailing list