max(), sum(), next()

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Sep 3 10:06:54 EDT 2008


 <bearophileHUGS at lycos.com> wrote:
>Empty Python lists [] don't know the type of the items it will
>contain, so this sounds strange:
>
>>>> sum([])
>0

>>> help(sum)
sum(...)
    sum(sequence, start=0) -> value

>>> sum(range(x) for x in range(5))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> sum((range(x) for x in range(5)), [])
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

... so the list might not know what type it contains, but sum
does. And if you don't tell it, it makes a sensible guess. And
it *is* a case where refusing the temptation to guess is the
wrong thing: how many times would you use sum to do anything
other than sum numeric values? And how tedious would it be to
have to write sum(..., 0) for every other case? Particularly
bearing in mind:

>>> sum(["a", "b"], "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list