Tip 25 sum() Almost Anything

Pythonic Programming — by Dmitry Zinoviev (34 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Use Slicing to Reverse and Split | TOC | Transpose with zip() 👉

★2.7, 3.4+ The built-in function sum is an excellent tool for summing up all numbers in an iterable and for operations dependent on such summation. For example, you can easily calculate the mean of a set even if you do not have access to statistics, numpy, scipy, or a similar module:

​ data = {1, 1, 1, 1, 2, 3} ​# set() eliminates duplicates​
​ mean = sum(data) / len(data)
​=> ​2.0​

Not so well known is the fact that sum is an optimized accumulator loop. You can think of it as:

​ ​def​ ​sum​(iterable, init=0):
​ ​for​ x ​in​ iterable:
​ init += x
​ ​return​ x

(This is not the actual implementation of sum, but it conveys its spirit.) Note that the optional parameter init by default equals 0 because we used sum to add numbers. If you change init to something else, you can accumulate almost any iterable whose members support the plus operator — for example, a list of tuples or a list of lists:

​ sum([(1, 2, 3), (4, 5, 6)], ())​=> ​(1, 2, 3, 4, 5, 6)​​ sum(([1, 2, 3], [4, 5, 6]), [])​=> ​[1, 2, 3, 4, 5, 6]​

There is one notable exception: sum does not allow you to concatenate a collection of strings. Concatenating a…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.