ReduceΒΆ

Another common form of the accumulator pattern is to combine or summarize all the items in a list.

For example, we can count the items in a list, or add them all up.

These particular operations, counting and summing, are so commonly performed that python provides built-in functions, len and sum

There’s also a built-in function max that works analogously, aggreating a list of numbers by keeping the largest one.

Another common accumulation that combines all the elements is to take a list of strings and concatenate them all together, separating them with some separator such as a comma or, in the example below, –.

Again, this way of combining lists of strings is so common that python has a built-in way to do it, in this case the join method. It’s invoked in a slightly strange way because join is a method of string class, not a method of the list class. The string to invoke the method on is the separator to be used in between each of the elements. The list of strings that are to be concatenated together is passed as a parameter.

More generally, python provides a function reduce which takes a list and produces a combined value from all the elements. Check out the documentation. The first parameter is a function that combines a result-so-far with the next element of a list, producing a new result-so-far. The second parameter is the list to be aggregated. An optional third parameter is the initial value for the accumulator variable. If it’s not provided, the first element of the list is used as the intitial value.

All of the specific accumulations that you’ve seen before can be expressed compactly using the reduce function, though it may take a little decoding to understand exactly what they do.

Of course, it’s easier to understand code using the more specific functions len, sum, max, and join, so you should use those rather than reduce whenever you can. But sometimes you want to make a custom aggregator for which there is no built-in. For example, from here’s a solution to a question from the Winter 2014 midterm exam.

Next Section - Zip