sum() requires number, not simply __add__

Stefan Behnel stefan_ml at
Thu Feb 23 16:42:22 EST 2012

Chris Rebert, 23.02.2012 22:32:
> On Thu, Feb 23, 2012 at 1:19 PM, Buck Golemon <buck at> wrote:
>> I feel like the design of sum() is inconsistent with other language
>> features of python. Often python doesn't require a specific type, only
>> that the type implement certain methods.
>> Given a class that implements __add__ why should sum() not be able to
>> operate on that class?
> The time machine strikes again! sum() already can. You just need to
> specify an appropriate initial value (the empty list in this example)
> for the accumulator :
> Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
> [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> sum([[1,2],[3,4]], [])
> [1, 2, 3, 4]

I know that you just meant this as an example, but it's worth mentioning in
this context that it's not exactly efficient to "sum up" lists this way
because there is a lot of copying involved. Each adding of two lists
creates a third one and copies all elements into it. So it eats a lot of
time and space.


More information about the Python-list mailing list