sum works in sequences (Python 3)
Neil Cerutti
neilc at norwich.edu
Wed Sep 19 11:06:43 EDT 2012
On 2012-09-19, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> It notes in the doc string that it does not work on strings:
>
> sum(...)
> sum(sequence[, start]) -> value
>
> Returns the sum of a sequence of numbers (NOT strings) plus
> the value of parameter 'start' (which defaults to 0). When
> the sequence is empty, returns start.
>
> I think this restriction is mainly for efficiency. sum(['a',
> 'b', 'c', 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c'
> + 'd' + 'e', which is an inefficient way to add together
> strings. You should use ''.join instead:
While the docstring is still useful, it has diverged from the
documentation a little bit.
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().
Are iterables and sequences different enough to warrant posting a
bug report?
--
Neil Cerutti
More information about the Python-list
mailing list