Splitting lists

Ferenczi Viktor cx at cx.hu
Wed Feb 26 22:10:17 EST 2003


Are there any fast, simple and elegant method to split a list by a filter
function?

My current solutions with their shortcomings:

# Common definitions:
lst=range(10)
def fn(x): return x<5

# Solution 1:
tl=[e for e in lst if fn(e)]
fl=[e for e in lst if not fn(e)]
# fn(e) must be evaluated twice, list must be traversed two times

# Solution 2:
tl=[]
fl=[]
for e in lst:
    if fn(e): tl.append(e)
    else: fl.append(e)
# Relatively slow

# Solution 3:
cl=[(e,fn(e)) for e in lst]
tl=[e[0] for e in cl if e[1]]
fl=[e[0] for e in cl if not e[1]]
# Eats up memory, list must be traversed three times

Is there any internal function to do the above?

I need something like: tl,fl=lst.split(fn)

Thanks: Complex







More information about the Python-list mailing list