Splitting lists

Steven Taschuk staschuk at telusplanet.net
Thu Feb 27 21:14:38 CET 2003

Quoth Létezõ:
> Thanks to Steven for the performance analysis and Alex & Duncan for the
> their more impressive solutions. It would be interesting to insert the new
> "impressive" solutions into the performace test loop. Which is the fastest?

Short and long list trials:

    viktor1           9.56   9.17
    viktor2           8.60   8.30
    viktor2lookup     6.00   5.72
    viktor3          12.08  14.19
    duncan            8.70   8.49
    duncanlookup      6.04   5.76
    alex              6.47   6.18

(The difference between viktor2lookup and duncanlookup is within
experimental error.  Other differences are significant.)

Code follows, so you can see how to do this yourself.

import time

def viktor1(lst, condition):
	tl = [e for e in lst if condition(e)]
	fl = [e for e in lst if not condition(e)]
	return tl, fl

def viktor2(lst, condition):
	tl = []
	fl = []
	for e in lst:
		if condition(e):
	return tl, fl

def viktor2lookup(lst, condition):
	addt = tl.append
	addf = fl.append
	for e in lst:
		if condition(e):
	return tl, fl

def viktor3(lst, condition):
	cl = [(e, condition(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]]
	return tl, fl

def duncan(lst, condition):
	fl = []
	tl = [x for x in lst if condition(x) or fl.append(x)]
	return tl, fl

def duncanlookup(lst, condition):
	fl = []
	addf = fl.append
	tl = [x for x in lst if condition(x) or addf(x)]
	return tl, fl

def alex(lst, condition):
	tl = []
	fl = []
	appenders = tl.append, fl.append
	for e in lst:
		appenders[not condition(e)](e)
	return tl, fl

def timetrial(splitfunc, condition, listsize, iterations):
	lst = range(listsize)
	start = time.clock()
	for i in range(iterations):
		splitfunc(lst, condition)
	end = time.clock()
	return end - start

if __name__ == '__main__':
	for f in (viktor1, viktor2, viktor2lookup,
			viktor3, duncan, duncanlookup, alex):
		print '%-15s %6.2f %6.2f' % (f.__name__,
			timetrial(f, lambda x: x < 5, 100, 5000),
			timetrial(f, lambda x: x < 5, 5000, 100))

Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1

More information about the Python-list mailing list