sum for sequences?
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Thu Mar 25 03:34:51 EDT 2010
On Wed, 24 Mar 2010 23:50:23 -0700, TomF wrote:
> On 2010-03-24 14:07:24 -0700, Steven D'Aprano
> <steven at REMOVE.THIS.cybersource.com.au> said:
>> On Wed, 24 Mar 2010 15:29:07 +0000, kj wrote:
>>
>>> Is there a sequence-oriented equivalent to the sum built-in? E.g.:
>>>
>>> seq_sum(((1, 2), (5, 6))) --> (1, 2) + (5, 6) --> (1, 2, 5, 6)
>>>
>>> ?
>>
>> Yes, sum.
>>
>> help(sum) is your friend.
>
> You might not want to be so glib. The sum doc sure doesn't sound like
> it should work on lists.
>
> Returns the sum of a sequence of numbers (NOT strings) plus the
> value of parameter 'start' (which defaults to 0).
What part of that suggested to you that sum might not be polymorphic?
Sure, it says numbers (which should be changed, in my opinion), but it
doesn't specify what sort of numbers -- ints, floats, or custom types
that have an __add__ method. It also singles out strings as excluded. Why
would you need to explicitly exclude strings, since they're not numbers,
if sum *only* works with numbers?
E.g. help(math.sin) could have said this, but doesn't:
Return the sine of x (NOT a dictionary)
It doesn't need to, because dicts aren't exceptional: sin doesn't work on
anything *but* numbers. There's no __sin__ method to call on arbitrary
types.
The fact that sum does single out strings is a clear sign that strings
are treated as exceptional and suggests strongly that summing arbitrary
types should work. I'm not saying that help(sum) explicitly states that
it works with lists (it clearly doesn't), but it does suggest the
possibility and makes the experiment worth trying.
I'll also note that the Fine Manual makes it even more clear that sum is
polymorphic:
http://docs.python.org/library/functions.html#sum
--
Steven
More information about the Python-list
mailing list