sum(strings)

Alex Martelli aleax at aleax.it
Thu Jun 19 19:01:16 CEST 2003


Duncan Booth wrote:
   ...
> I can see that for adding strings you would be better to use str.join, but
> the explicit type check seems to be very un-pythonic.

Practicality beats purity.

> I would have thought a simpler implementation would be:
> 
> def sum(seq, start=sentinal):
>     iterable = iter(seq)
>     if start is sentinal:
>         result = iterable.next()
>     else:
>         result = start
> 
>     for item in iterable:
>         result += item
>     return result
> 
> which has the advantage that you can sum anything addable without
> specifying a start value.

...and the HUGE practical disadvantage of strongly encouraging
a horde of newbies to rush into the worst performance trap that
is waiting for them in Python -- putting a lot of small strings
together into a big string with +=.  This is known as an
"attractive nuisance" and may make you liable for the resulting
damages;-).  No, if sum accepted a sequence of strings it WOULD
have to delegate to ''.join in that case -- and I just couldn't
find an elegant and totally general way to do that.  Thus, using
sum as yet another occasion to remind newbies about the wonders
of ''.join was deemed to be the best practical solution.


Alex





More information about the Python-list mailing list