[Python-ideas] Intermediate Summary: Fast sum() for non-numbers
Stefan Behnel
stefan_ml at behnel.de
Thu Jul 18 17:48:05 CEST 2013
Steven D'Aprano, 18.07.2013 04:52:
> On 18/07/13 04:07, Stefan Behnel wrote:
>> M.-A. Lemburg, 15.07.2013 09:11:
>>> I don't understand why people try to use sum() for anything
>>> other than a sequence of numbers.
>>>
>>> If you want to flatten a list, use a flatten function.
>>
>> +1
>>
>> And, while we're at it, we can just as well ask why
>>
>> sum([[1,2,1], [2,1,2], [3,4,5,[6,7]], [[4,3], 1]])
>>
>> doesn't return 42.
>
>
> Why would it return 42? List addition is not defined as element-by-element
> addition, it is defined as concatenation. To put it another way, since [1,
> 2, 1] + [2, 1, 2] returns [1, 2, 1, 2, 1, 2], not 9, sum() returns the same.
>
>
>> IMHO, this would make a lot more sense than returning a
>> concatenated list.
>
> I'm afraid that this doesn't make sense to me.
The point I was trying to make is that a "sum" is well defined for numbers
but not for lists, so even a recursive sum over lists of lists makes more
sense than calling sum() on a sequence of lists and expecting it to
concatenate those lists. I really don't see the link between summing up
items and concatenating them. If the function was called "concatenate()",
then, yes, ok, I'd expect it to concatenate lists that I feed into it. But
it's called sum(). And it's called that because the name describes what it
does. The mere attempt to "sum" lists is just so misguided that it's really
not worth any discussion, especially not about making it easier!
Just to be clear, I definitely wasn't proposing to extend sum() to support
recursive summing.
Stefan
More information about the Python-ideas
mailing list