sum() vs. loop
Steve Keller
keller.steve at gmx.de
Sun Oct 10 10:19:40 EDT 2021
Christian Gollwitzer <auriocus at gmx.de> writes:
> > 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
> > [...]
>
> The first version constructs a list, sums it up and throws the list
> away, while the second version only keeps the running sum in
> memory. How about a generator expression instead, i.e.
>
>
> sum((a * b for a, b in zip(seq1, seq2)))
Ah, of course. Much cleaner and I should have seen that myself.
Thanks.
BUT
> (untested) ?
I have tested it and with () instead of [] it's even slower:
explicit loop: 37s ± .5s
sum([...]) 44s ± .5s
sum((...)) 47.5s ± .5s
Now completely surprised.
Steve
More information about the Python-list
mailing list