[Python-ideas] Intermediate Summary: Fast sum() for non-numbers
Steven D'Aprano
steve at pearwood.info
Thu Jul 18 04:52:36 CEST 2013
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. What you're showing is neither list addition as it is defined now (concatenation), nor element-by-element addition, both of which would raise exceptions, but a recursive flatten immediately followed by a summation. And this is just after you agreed that if you want to flatten a list, you should call a flatten function, not sum!
Regardless of how sum() might have been defined, or should have been designed, or whether list addition should be defined as element-by-element addition rather than concatenation, sum() has been around for about ten years now, and we're constrained by backwards compatibility.
If anyone wants to seriously argue for breaking backwards compatibility, please don't argue here until you have got at least the beginnings of a PEP written.
--
Steven
More information about the Python-ideas
mailing list