I found this question Generators vs List Comprehension performance in Python and instead of cProfile I use timeit.
from timeit import timeit
import cProfile
print timeit('sum([i for i in range(9999999)])', number=1)
print timeit('sum((i for i in range(9999999)))', number=1)
print cProfile.run('sum([i for i in xrange(9999999)])')
print cProfile.run('sum((i for i in xrange(9999999)))')
Result is
LC timeit 0.728941202164
G timeit 0.643975019455
LC cProfile 3 function calls in 0.751 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.673 0.673 0.751 0.751 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.078 0.078 0.078 0.078 {sum}
None
G cProfile 10000003 function calls in 1.644 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 0.843 0.000 0.843 0.000 <string>:1(<genexpr>)
1 0.000 0.000 1.644 1.644 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.801 0.801 1.644 1.644 {sum}
I believe generator should better than list comprehension but why in this case the result is not clear. My question is which one is better to write
sum((i for i in list_of_i)) # Which use 1 loop
vs
sum([i for i in list_of_i]) # Which seem to took 2 loop: 1 for list create and one for sum