max(), sum(), next()

castironpi castironpi at gmail.com
Wed Sep 3 19:34:28 EDT 2008


On Sep 3, 7:48 am, 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:
>
> >>> sum(s for s in ["a", "b"] if len(s) > 2)
>
> 0
>
> In a statically typed language in that situation you may answer the
> initializer value of the type of the items of the list, as I do in the
> sum() in D.
>
> This sounds like a more correct/clean thing to do:
>
> >>> max([])
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: max() arg is an empty sequence
>
> So it may be better to make the sum([]) too raise a ValueError, in
> Python 3/3.1 (if this isn't already true). On the other hand often
> enough I have code like this:
>
> >>> max(fun(x) for x in iterable if predicate(x))
>
> This may raise the ValueError both if iterable is empty of if the
> predicate on its items is always false, so instead of catching
> exceptions, that I try to avoid, I usually end with a normal loop,
> that's readable and fast:
>
> max_value = smallvalue
> for x in iterable:
>     if predicate(x):
>         max_value = max(max_value, fun(x))
>
> Where running speed matters, I may even replace that max(max_value,
> fun(x)) with a more normal if/else.
>
> A possible alternative is to add a default to max(), like the next()
> built-in of Python 2.6:
>
> >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue)
>
> This returns smallvalue if there are no items to compute the max of.
>
> Bye,
> bearophile

Two thoughts:
1/ 'Reduce' has a 'default' argument-- they call it 'initial'.

>>> reduce( max, [ 0, 1, 2, 3 ] )
3
>>> reduce( max, [ 0, 1, 2, 'a' ] )
'a'
>>> reduce( max, [ 0, 1, 2, 'a', 'b' ] )
'b'

2/ Introduce a 'max' class object that takes a default type or default
argument.  Query the default for an 'additive' identity, or query for
a 'comparitive' identity, comparisons to which always return true; or
call the constructor with no arguments to construct one.



More information about the Python-list mailing list