Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Neil Cerutti Newsgroups: comp.lang.python Subject: Re: sum works in sequences (Python 3) Date: 19 Sep 2012 15:06:43 GMT Organization: Norwich University Lines: 36 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 8bit X-Trace: individual.net xjXV21wOa3TMlNK5jihDBAfV8lqkzUJm0F3Y2HNvxfM3CWL3T9hCXSTuzbRv5GOmEw Cancel-Lock: sha1:TjCMMhcg0TSNUbjD0OszpC7BI/M= User-Agent: slrn/0.9.9p1/mm/ao (Win32) Xref: csiph.com comp.lang.python:29498 On 2012-09-19, Ian Kelly 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