looping for a sum versus summing a list comprehension
Question: In the sort of calculations I do, I often encounter the need to sum some
expression over (at least) one list. Let's say I want to find the sum of x^2
for x in some list L. Is there a significant difference between run times of

    
    
    sum([val**2 for val in L])
    

versus

    
    
    total = 0
    for val in L:
        total+=val**2
    

and would this change if I had a more complicated expression to sum? I'm not
concerned about the memory issues associated with creating a list, but cleaner
code and faster run time matter.

I'm basically wondering whether the optimization that people have probability
done to list generators and to sum would get me a faster code - doing the loop
in C rather than python.

**edit** for anyone searching for this, the answer turns out to be that
converting to numpy arrays and then doing the calculation is fastest of all.


Answer: The easiest and most certain answer to do is just test it:

    
    
    import timeit
    import numpy as np
    
    L = range(1000)
    M = np.arange(1000)
    
    def f0():
        sum([val**2 for val in L])
    
    def f1():
        total = 0
        for val in L:
            total+=val**2    
    
    def f2():
        np.sum(M*M)
    
    print timeit.timeit("f0()", setup="from __main__ import f0, f1, f2, L, M", number=100)
    print timeit.timeit("f1()", setup="from __main__ import f0, f1, f2, L, M", number=100)
    print timeit.timeit("f2()", setup="from __main__ import f0, f1, f2, L, M", number=100)
    
    # 0.015289068222
    # 0.00959897041321
    # 0.000958919525146
    

The times have a similar ratio if 1M is used instead of 1K (here I also used
`number=10` so I didn't have to wait):

    
    
    # 1.21456193924
    # 1.08847117424
    # 0.0474879741669
    

That is, the two pure Python approaches are about the same, and using numpy
speeds up the calculation 10-20x.

