sum() vs. loop

Chris Angelico rosuav at
Mon Oct 11 18:05:51 EDT 2021

On Tue, Oct 12, 2021 at 9:02 AM Stefan Ram <ram at> wrote:
> Steve Keller <keller.steve at> writes:
> >Now completely surprised.
>   I have observed that here the generator-based sum() call
>   is slower if both seq1 and seq2 have a length of 1000, but
>   faster if both seq1 and seq2 have 10000000 entries each
>   (with float entries).
>   However, in any case, the direct for-loop still is fastest.
>   Maybe, calling "next()" (actually, "PyIter_Next" in C) on
>   an iterator has some overhead compared to just evaluating
>   an expression in a loop.

There's overhead whichever way you do it, and ultimately, it depends
on what you're doing. The genexp is effectively a callback into Python
code. The list comp requires preconstruction of the entire list. The
plain for loop involves summing by picking up and putting down in
Python code rather than doing that in C. The only way to know which is
fastest is to try them all :)


More information about the Python-list mailing list