-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Functional Python Programming, 3rd edition
By :

The len()
and sum()
functions provide two simple reductions—a count of the elements and the sum of the elements in a sequence. These two functions are mathematically similar, but their Python implementation is quite different.
Mathematically, we can observe this cool parallelism:
The len()
function returns the sum of ones for each value in a collection, X: ∑ x∈X1 = ∑ x∈Xx0.
The sum()
function returns the sum of each value in a collection, X: ∑ x∈Xx = ∑ x∈Xx1.
The sum()
function works for any iterable. The len()
function doesn’t apply to iterables; it only applies to sequences. This little asymmetry in the implementation of these functions is a little awkward around the edges of statistical algorithms.
As noted above, for empty sequences, both of these functions return a proper additive identity value of zero:
>>> sum(())
0
>>> len(()) ...