What is the problem with reduce()?

There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it.

What am I missing? What is the problem with reduce()?

Asked by: Kate695 | Posted: 05-10-2021

Answer 1

As Guido says in his The fate of reduce() in Python 3000 post:

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. 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 is an excellent example of a confusing reduce in the Functional Programming HOWTO article:

Quick, what's the following code doing?

total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

You can figure it out, but it takes time to disentangle the expression to figure out what's going on. Using a short nested def statements makes things a little bit better:

def combine (a, b):
    return 0, a[1] + b[1]

total = reduce(combine, items)[1]

But it would be best of all if I had simply used a for loop:

total = 0
for a, b in items:
    total += b

Or the sum() built-in and a generator expression:

total = sum(b for a,b in items)

Many uses of reduce() are clearer when written as for loops.

Answered by: Emily960 | Posted: 06-11-2021

Answer 2

reduce() is not being removed -- it's simply being moved into the functools module. Guido's reasoning is that except for trivial cases like summation, code written using reduce() is usually clearer when written as an accumulation loop.

Answered by: Owen224 | Posted: 06-11-2021

Answer 3

People worry it encourages an obfuscated style of programming, doing something that can be achieved with clearer methods.

I'm not against reduce myself, I also find it a useful tool sometimes.

Answered by: Alina711 | Posted: 06-11-2021

Answer 4

The primary reason of reduce's existence is to avoid writing explicit for loops with accumulators. Even though python has some facilities to support the functional style, it is not encouraged. If you like the 'real' and not 'pythonic' functional style - use a modern Lisp (Clojure?) or Haskell instead.

Answered by: Kate128 | Posted: 06-11-2021

Answer 5

Using reduce to compute the value of a polynomial with Horner's method is both compact and expressive.

Compute polynomial value at x. a is an array of coefficients for the polynomial

def poynomialValue(a,x):
   return reduce(lambda value, coef: value*x + coef, a)

Answered by: Abigail505 | Posted: 06-11-2021

Similar questions

Why python reduce() skip over the None element?

I tried to get the home site of a url. Firstly I used a for loop and achieve the goal. home = '' my_url = 'http://www.mysite.com/subdir/subdir2/index.html' for item in my_url.split('/')[:3]: home += item + '/' print home and I can get 'http://www.mysite.com/' Then I come across reduce() which I had never used before. So I get it a shot,here is the c...

python - Trying to use reduce() and lambda with a list containing strings

I'm trying to use pythons reduce function on a list containing strings of integers. print int("4") \\Gives me 4 Good print reduce(lambda x, y: x*y, [2, 3, 4]) \\Gives me 24 Good print reduce(lambda x, y: x*int(y), ['2', '3', '4']) \\Gives me 222222222222 What?? I assume that reduce is giving the lambda function something that isn't the actual string in the list? I have no idea why I'...

python - How to refer to the whole array within reduce()?

What I have: array = original_array[:] result = reduce(lambda a,b: some_function(b,array), array) What I want: I want to get rid of the array = original_array[:] statement. Ideally I would simply replace the array parameter inside reduce() with original_array[:], but I need it inside lambda as well. Is there a way to refer to the array parameter from wit...

python - reduce() doesn't seem to return a number, or else .index() isn't working like it's supposed to

I have a function that is supposed to do the following: take in a list of lists, and a list of numerical weights. Then, take the weighted average of every bottom-level item in the list of lists, with the first item in the list of weights being used to weight the first list of things, the second item in the list of weights being used to weight the second list, etc. It's like a function that simply takes the weighted average...

reduce() hstack python

I am trying to use reduce() function to create a function hstack() which horizontally stacks multiple arrays. As a simple example, lets say >>>>M=eye((4)) >>>>M array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>>>hstack([M,M]) array([[ 1., 0., 0., 0., 1., 0., 0., 0.], [ 0., 1., ...

working of Reduce() in Python

In [1]: a = [4,5,6] In [2]: reduce(lambda x,y:x,a) Out[2]: 4 In [3]: reduce(lambda x,y:x+1,a) Out[3]: 6 In [4]: reduce(lambda x,y:x+2,a) Out[4]: 8 In [5]: reduce(lambda x,y:x+3,a) Out[5]: 10 I understand first reduce operation but I'm getting confused with rest 3 lines. for 2nd reduce reduce(lambda x,y:x+1,a) output should be 5,shouldn't it? I've already read the docs

python fuzzy reduce() has no initial value

I am trying a program to find the average fuzzy ratio of the word good within the lines of all text files in a directory and I am getting the following exception: Traceback (most recent call last): File "C:/Python27/hukj.py", line 28, in <module> my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file)) TypeError: reduce() of empty sequence with...

python - What does lambda x, (y, z): x | (z << y) plays a part in reduce()?

The code is as below: reduce(lambda x, (y, z): x | (z &lt;&lt; y), enumerate(map(lambda i: 0 if i &lt; avg else 1, im.getdata())), 0) What makes me confused is the first argument of reduce() lambda x, (y, z): x | (z &lt;&lt; y) I get the meaning of other two arguments: enumerate(map(lambda i: 0 if i &lt; avg else...

python - When would you use reduce() instead of sum()?

I began learning functional programming recently, and came up with this example when attempting to calculate my quiz average for a class. The example I came up with is: scores = [90, 91, 92, 94, 95, 96, 97, 99, 100] def add(num1, num2): '''returns the sum of the parameters''' return num1 + num2 import operator timeit reduce(add, scores) / len(scores) #--&gt; 1000000 loops, best of 3: 79...

apache spark - Reduce() after filter() in Python?

I have question about two functions in python: reduce() and filter(). Can we use reduce() after filter()? I used boston datasets in sklearn. x = load_boston() x_target = x.target xx = filter(lambda x: x &gt; 20, x_target) And it's working fine. Next I want use reduce() function to sum up values in xx. from functools import reduce xxx = reduce(lambda x,y: x+y, xx)

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python