[Python-ideas] Fast sum() for non-numbers
Serhiy Storchaka
storchaka at gmail.com
Wed Jul 3 11:19:02 CEST 2013
03.07.13 06:24, Mathias Panzenböck написав(ла):
> Such a function is very tiny:
>
> >>> import operator
> >>> isum = lambda *args: reduce(operator.iadd,*args)
>
> But this might be unexpected:
>
> >>> l = []
> >>> l2 = isum([[1,2,3]]*1000000, l)
>
> l is now changed. In fact l == l2. I guess this could cause more
> troubles than
> it's good for if the user expects tha current behaviour. I don't think
> such an
> incompatible API change can ever be made. But one could maybe include isum,
> maybe just as recipe in the documentation or in itertools or somewhere.
Sergey's code is more smart. It equals to the following Python code:
def sum(iterable, start=0):
it = iter(iterable)
try:
x = next(it)
except StopIteration:
return start
result = start + x
for x in it:
result += x
return result
More information about the Python-ideas
mailing list