sum() requires number, not simply __add__

Chris Rebert clp2 at
Thu Feb 23 16:32:45 EST 2012

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]


More information about the Python-list mailing list