Search code examples
pythonfunctional-programming

Python alternative to reduce()


There is a semi-famous article written by Guido himself hinting that reduce() should go the way of the dodo and leave the language. It was even demoted from being a top-level function in Python 3 (instead getting stuffed in the functools module).

With many other functional programming staples (map, etc) common clear alternatives are available. For example, most of the time a map() is better written as a list comprehension.

What I'd like to know is if there is a similar "more pythonic" alternative to the reduce function. I have a bit of a functional programming background (ML in particular), so reduce() often springs to my mind when thinking of a solution, but if there's a better way to do them (short of unrolling a reduce call into a for loop) I'd like to know.


Solution

  • As Guido's linked article says, you should just write an explicit for loop if you want to avoid reduce(). You can replace the line

    result = reduce(function, iterable, start)
    

    by

    result = start
    for x in iterable:
        result = function(result, x)