[Python-ideas] Fast sum() for non-numbers

Nick Coghlan ncoghlan at gmail.com
Wed Jul 3 10:14:46 CEST 2013


On 3 July 2013 14:40, Andrew Barnert <abarnert at yahoo.com> wrote:

> On Jul 2, 2013, at 20:24, Mathias Panzenböck <
> grosser.meister.morti at gmx.net> wrote:
>
> > Such a function is very tiny:
> >
> > >>> import operator
> > >>> isum = lambda *args: reduce(operator.iadd,*args)
> >
> > But this might be unexpected:
> >
> > >>> l = []
> > >>> l2 = isum([[1,2,3]]*1000000, l)
> >
> > l is now changed. In fact l == l2.
>
> He explicitly suggested making one copy, before looping. So, this:
>
>    sum([[1,2,3]]*1000000, l)
>
> Has to mean:
>
>     reduce(operator.iadd, [[1,2,3]]*1000000, copy.copy(l))
>
> So, it's not quite a one-liner, and it doesn't have this problem.
>
> > But one could maybe include isum,
> > maybe just as recipe in the documentation or in itertools or somewhere.
>
> This sounds like a good idea. Possibly even both versions, with and
> without the copy.
>
> While we're at it, I've always wished sum and reduce used the same name
> for their start/initial parameter. If we're going to be changing one (which
> I suspect we probably aren't, but just in case...), is this a good time to
> campaign for renaming the param?
>

reduce only just survived being culled completely in the Python 3
transition, so if one was going to change it would be reduce. Our
perspective is that if you're considering using reduce, you should remember
you're writing Python rather than a pure functional language and switch to
a loop instead. (By contrast, map and filter are nice alternatives to a
generator expression if you are just applying an existing function)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130703/77b75068/attachment.html>


More information about the Python-ideas mailing list