# [Python-Dev] Rationale for sum()'s design?

Nick Coghlan ncoghlan at iinet.net.au
Tue Mar 15 13:21:07 CET 2005

```Guido van Rossum wrote:
> I think the conclusion should be that sum() is sufficiently
> constrained by backwards compatibility to make "fixing" it impossible
> before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is
> only used for empty lists.

1. When omitting the second argument, would supplying an empty list return 0,
None or raise an exception?

The last seems most reasonable, as otherwise the function is guessing about what
the programmer wants.

2. How would the initial value that forms the basis of summation be built for
non-empty sequences?

The first element can't be used directly, as that would mutate the first element
for a sequence of lists or other mutable objects.

Using the default constructor for the type of the first element in the iterable
has its own problem. With the second argument being ignored for non-empty
iterables, it makes it impossible to use sum() with classes that do have an
additive identity, but it isn't created by the default constructor. At the
moment, such classes can be used by supplying the additive identity as the
second argument to sum().

Both of the above cases can be supported by an approach that says:

a. If a second argument is not supplied, and the iterable is empty, raise an
exception.

b. If a second argument is not supplied, and the iterable is not empty, use the
default constructor of the type of the first argument as the initial value

c. If a second argument is supplied, and the iterable is empty, return the
second argument.

d. If a second argument is supplied, and the iterable is not empty, use the
second argument as the initial value.

This scheme can be made backwards compatible with the current sum() by switching
point a. from 'raise an exception' to 'return zero'.

With the above compatibility change, getting all the way back to the existing
sum() behaviour only requires changing point b. to say "use zero as the initial
value"

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
```