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

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jul 11 16:31:48 CEST 2013


On 11 July 2013 14:20, Ron Adam <ron3200 at gmail.com> wrote:
>
> On 07/11/2013 06:05 AM, Oscar Benjamin wrote:
>> On 11 July 2013 11:47, Ron Adam<ron3200 at gmail.com> wrote:
>
>    chain(iters)        # better in most cases...

I think you mean chain.from_iterable rather than chain

> I'd like to see chain as a builtin in any case.

chain.from_iterable should be the builtin not chain.

> How do you feel about adding the ability of sum to sum vectors or lists of
> values to each other?
>
> sum([[x1, y1], [x2, y2], ...])  --->  [x1+x2, y1+y2]

That's the beauty of it. sum() already sums anything you want as long
as __add__ is implemented. If I wanted to do the above with some
vectors I would probably use numpy arrays which have precisely the
__add__ method you want:

>>> import numpy as np
>>> arrays = [
...   np.array([1, 2, 3]),
...   np.array([2, 3, 4]),
...   np.array([3, 4, 5]),
... ]
>>> arrays
[array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5])]
>>> sum(arrays)
array([ 6,  9, 12])

This is possible because of the simplicity of the core algorithm in
sum() i.e. just calling 'total = total + item' in a loop. Anyone who
wants to use sum() with their own type can already do so. Earlier you
seemed to be advocating changing that by restricting the types that
sum() accepts.


Oscar


More information about the Python-ideas mailing list