max(), sum(), next()

Terry Reedy tjreedy at udel.edu
Wed Sep 10 18:36:46 EDT 2008



Mensanator wrote:
> Are there situations where the sum of an empty
> list should NOT be 0? Of course there are.

Python Philosopy (my version, for this discussion):
   Make normal things easy; make unusual or difficult things possible.

Application:
   Sum([]) == 0 is normal (90+% of cases).  Make that easy (as it is).
   For anything else:
     if seq: s = sum(s, base)
     else: <whatever, including like raise your desired exception>
   which is certainly pretty easy.

> Can sum() handle those cases?

The developers choose what they thought would be most useful across the 
spectrum of programmers and programs after some non-zero amount of 
debate and discussion.

 >  No, it can't, I have to write
> my own definition if I want that behaviour.

Or wrap your calls.  In any case, before sum was added as a convenience 
for summing numbers, *everyone* has to write their own or use reduce.

Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be 
the most common use of reduce.  Sum(s,start) replaces the much less 
common reduce(lambda x,y: x+y, s, start).

Reduce(S, s), where S = sum function, raises an exception on empty s.
So use that and you are no worse off than before.

However, a problem with reduce(S,s) is that it is *almost* the same as 
reduce(S,s,0).  So people are sometimes tempted to omit 0, especially if 
they are not sure if the call might be reduce(S,0,s) (as one argument 
says it should be -- but that is another post).  But if they do, the 
program fails, even if it should not, if and when s happens to be empty.

> There's no reason
> why sum([]) and sum([],0) have to mean the same thing at the
> exclusion of a perfectly valid alternative definition.

'Have to', no reason.  'Should', yes there are at least three reasons. 
1. Python functions generally return an answer rather than raise an 
exception where there is a perfectly valid answer to return.
2. As a general principle, something that is almost always true should 
not need to be stated over and over again.  This is why, for instance, 
we have default args.
3. As I remember, part of the reason for adding sum was to eliminate the 
need (with reduce) to explicitly say 'start my sum at 0' in order to 
avoid buggy code.  In other words, I believe part of the reason for 
sum's existence is to avoid the very bug-inviting behavior you want.

Terry Jan Reedy




More information about the Python-list mailing list