max(), sum(), next()

MRAB google at mrabarnett.plus.com
Wed Sep 3 18:40:35 EDT 2008


On Sep 3, 8:18 pm, Laszlo Nagy <gand... at shopzeus.com> wrote:
> bearophileH... at lycos.com wrote:
> > Empty Python lists [] don't know the type of the items it will
> > contain, so this sounds strange:
>
> >>>> sum([])
>
> > 0
>
> > Because that [] may be an empty sequence of someobject:
>
> You are right in that sum could be used to sum arbitrary objects.
> However, in 99.99% of the cases, you will be summing numerical values.
> When adding real numbers, the neutral element is zero. ( X + 0 = X) It
> is very logical to return zero for empty sequences.
>
> Same way, if we would have a prod() function, it should return one for
> empty sequences because X*1 = X. The neutral element for this operation
> is one.
>
> Of course this is not good for summing other types of objects. But how
> clumsy would it be to use
>
> sum( L +[0] )
>
> or
>
> if L:
> value = sum(L)
> else:
> value = 0
>
> instead of sum(L).
>
> Once again, this is what sum() is used for in most cases, so this
> behavior is the "expected" one.
>
> Another argument to convince you: the sum() function in SQL for empty
> row sets returns zero in most relational databases.
>
> But of course it could have been implemented in a different way... I
> believe that there have been excessive discussions about this decision,
> and the current implementation is very good, if not the best.
>
An alternative would be for the start value to default to None, which
would mean no start value. At the moment it starts with the start
value and then 'adds' the items in the sequence to it, but it could
start with the first item and then 'add' the following items to it.
So:

    sum([1, 2, 3]) => 6
    sum(["a", "b", "c"]) => "abc"

For backward compatibility, if the sequence is empty and the start
value is None then return 0.



More information about the Python-list mailing list