sum() vs. loop

Christian Gollwitzer auriocus at
Tue Oct 12 14:52:21 EDT 2021

Am 12.10.21 um 05:41 schrieb Dan Stromberg:
> On Mon, Oct 11, 2021 at 2:54 PM Steve Keller <keller.steve at> wrote:
>> I have found the sum() function to be much slower than to loop over the
>> operands myself:
>> def sum_products(seq1, seq2):
>>      return sum([a * b for a, b in zip(seq1, seq2)])
>> def sum_products2(seq1, seq2):
>>      sum = 0
>>      for a, b in zip(seq1, seq2):
>>          sum += a * b
>>      return sum

> It seems like the generator expression should be the fastest to me.  But
> writing for speed instead of writing for clarity is usually not a great
> idea.

Maybe, unless this was just a test, it can be fastest AND clearest with

  , seq2)

- in case that the sequence consists of floats and, in the best case, is 
already stored in a numpy array. Then you cannot beat this with Python 


More information about the Python-list mailing list