On Feb 23, 1:32 pm, Chris Rebert <c...@rebertia.com> wrote: > On Thu, Feb 23, 2012 at 1:19 PM, Buck Golemon <b...@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 -- http://mail.python.org/mailman/listinfo/python-list