Here are the speeds of the various versions on an old-ish Mac laptop:
$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(filter(lambda n : n % 2 == 0, domain))'
100000 loops, best of 3: 4.41 usec per loop
$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum([n for n in domain if n % 2 == 0])'
100000 loops, best of 3: 2.69 usec per loop
$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(n for n in domain if n % 2 == 0)'
100000 loops, best of 3: 2.86 usec per loop
Note that, while the genexp version is no doubt more cool, the listcomp is marginally faster (probably not by enough to worry about unless this code is in a tight inner loop you're striving to optimize the snot out of;-). As usual, the lambda
-based version is substantially slower, as others have mentioned -- lambda
is kind of a "poor relation" in Python:-(. ((Not that a def
ined function would perform noticeably better here, either))