sum() requires number, not simply __add__

Buck Golemon buck at yelp.com
Thu Feb 23 22:38:12 CET 2012


On Feb 23, 1:32 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Thu, Feb 23, 2012 at 1:19 PM, Buck Golemon <b... at yelp.com> 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]
>
> Cheers,
> Chris
> --http://rebertia.com

Thanks. I did not know that!

My proposal is still *slightly* superior in two ways:

1) It reduces the number of __add__ operations by one
2) The second argument isn't strictly necessary, if you don't mind
that the 'null sum' will produce zero.

def sum(values, base=0):
      values = iter(values)

      try:
          result = values.next()
      except StopIteration:
          return base

      for value in values:
          result += value

      return result



More information about the Python-list mailing list