Profiling, sum-comprehension vs reduce

Bas wegwerp at gmail.com
Sat Sep 13 12:00:12 EDT 2008


On Sep 13, 10:06 am, cnb <circularf... at yahoo.se> wrote:
> This must be because of implementation right? Shouldn't reduce be
> faster since it iterates once over the list?
> doesnt sum first construct the list then sum it?

No, sum also iterates the sequence just once and doesn't create a
list. It is probably implemented similar to

def sum(sequence, start=0):
    it = iter(sequence)
    total = start
    for i in it:
        total += i
    return i

but then implemented in C for speed. Reduce is probably implemented
pretty similar, but then with a random function instead of addition.
Make sure that you understand the difference between generator
expression and list comprehension, and that [f(x) for x in something]
is (almost) equal to list(f(x) for x in something), so you can emulate
a LC by using the list constructor on the equivalent GE.

HTH,
Bas



More information about the Python-list mailing list