[Python-ideas] Fast sum() for non-numbers
Ronald Oussoren
ronaldoussoren at mac.com
Wed Jul 10 08:34:28 CEST 2013
On 9 Jul, 2013, at 19:11, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Jul 9, 2013, at 6:42, Sergey <sergemp at mail.ru> wrote:
>
>> On Jul 8, 2013 Andrew Barnert wrote:
>>
>>> I'm -1 on adding special-casing for tuples that would not be
>>> available for any other immutable type.
>>
>> Ok, let's be honest, I don't like that special case too. :(
>> But when I had two options:
>>
>> 1. Make sum faster for everything BUT tuples and write in a manual:
>> ...
>> sum() is fast for all built-in types except `tuple`. For tuples
>> you have to manually convert it to list, i.e. instead of:
>> sum(list_of_tuples, tuple())
>> you have to write:
>> tuple(sum(map(list,list_of_tuples),[]))
>> or
>> tuple(itertools.chain.from_iterable(list_of_tuples))
>> ...
>>
>> 2. Implement just one (!) special case for the only type in python
>> needing it and write:
>> ...
>> sum() is fast for all built-in types!
>> ...
>>
>> I chose #2. Tuple is one of the most frequently used types in python,
>> and it's the only type that needs such a special case.
>>
>> Until someone writes a better solution: Practicality beats purity.
>> That was my motivation.
>
> #3 is for the docs to say what they currently say--sum is fast for numbers--but change the "not strings" to "not sequences", and maybe add a note saying _how_ to concatenate sequences (usually join for strings and chain for everything else).
Good idea, I hope Guido hasn't noticed that his time machine was gone for a while ;-)
<quote>
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().
</quote>
This is from http://docs.python.org/3/library/functions.html (and is in the python 2.7 version as well)
Ronald
More information about the Python-ideas
mailing list