I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list.
While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression:
python -m timeit -s "L = xrange(1000000)" "sum([1 for i in L if i & 1])"
10 loops, best of 3: 109 msec per loop
python -m timeit -s "L = xrange(1000000)" "sum(1 for i in L if i & 1)"
10 loops, best of 3: 125 msec per loop
I have also tried with L being a regular list, and different sizes, but in all cases the list comprehension wins.
What is the genexp doing that causes it to be slower compared to the listcomp that creates a new list with 1 million items...?
(Btw, the fastest way I found was: x = 1; len(filter(x.__and__, L))
. And yes, I know writing code like that kills kittens, I'm doing it for the fun of it)