Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 527
Adam Parkin Avatar asked Feb 28 '12 00:02

Adam Parkin


People also ask

Why was reduce removed from Python?

The arguments against reduce are that it tends to be misapplied, harms readability and doesn't fit in with the non-functional orientation of Python.

Is there a reduce function in Python?

Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.

Is reduce faster than for loop Python?

Indeed, the reduce is much faster than the for when using iadd in the for.

How do you decrease in Python?

The lower() method returns a string where all characters are lower case.


2 Answers

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) 
like image 115
Sven Marnach Avatar answered Sep 25 '22 19:09

Sven Marnach


What I'd like to know is if there is a similar "more pythonic" alternative to the reduce function.

Yes and no. It depends upon the use case.

In the linked article Guido suggests that most but not all reductions ought to be written as loops. There are limited circumstances in which he sees reduce as being applicable.

So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

There aren't a whole lot of associative operators. (Those are operators X for which (a X b) X c equals a X (b X c).) I think it's just about limited to +, *, &, |, ^, and shortcut and/or.

like image 38
kkurian Avatar answered Sep 21 '22 19:09

kkurian