sum works in sequences (Python 3)
Steve Howell
showell30 at yahoo.com
Wed Sep 19 11:37:00 EDT 2012
On Sep 19, 8:06 am, Neil Cerutti <ne... at norwich.edu> wrote:
> On 2012-09-19, Ian Kelly <ian.g.ke... 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?
>
Sequences are iterables, so I'd say the docs are technically correct,
but maybe I'm misunderstanding what you would be trying to clarify.
More information about the Python-list
mailing list