The following are the speeds of the various versions on a Mac 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 although the genexp version is undoubtedly steeper, the listcomp is slightly faster (perhaps not enough to worry about if this code is not in a tight inner loop that you are trying to optimize the snot). As usual, the lambda based version is significantly slower, as others have noted - lambda is a kind of "bad attitude" in Python :-(. (Not to mention that the def function is better here))
Alex martelli
source share