Accumulate function in python

Paul Rubin no.email at nospam.invalid
Mon Jul 19 14:45:33 EDT 2010


Brian Victor <homeusenet4 at brianhv.org> writes:
> def running_sum(result, current_value):
>     return result + [result[-1]+current_value if result else current_value]
>
> reduce(running_sum, x, [])

That is not really any good because Python lists are actually vectors,
so result+[...] actually copies the whole old list, making your function
take quadratic time.  It would be ok in a FP language where lists were
chains of cons nodes and result+[...] just allocated a single cons.

I think Peter Otten's solution involving a generator is the one most in
the current Python spirit.  It's cleaner (for my tastes) than the ones
that use things like list.append.



More information about the Python-list mailing list