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.
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.
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.
Indeed, the reduce is much faster than the for when using iadd in the for.
The lower() method returns a string where all characters are lower case.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With