31 points praptak 2 days ago 35 comments

eimrine 2 days ago | parent

Reduce requires knowing that the sum of zero entities is zero but the multiply of zero entities is one. They forget to throw the correct number and think that reduce() just do not work for them.

theamk 2 days ago | parent

At least in Python, I've found that "reduce" is very rarely needed. Most of the times, "sum" is enough, sometimes with "start" values customized (set it to [] to flatten an array for example). It is both easier to read, faster, and needs no imports. It also works great with list comprehensions - "sum(foo(x) for x in input if x > 5)" is much easier to read than reduce equivalent.

If you are multiplying, you are likely doing heavy math, and you'll be using numpy - which does not need reduce either.

If you are going to return a list of dict, then it's much faster to mutate the results, so using "reduce" will have significant performance implications (unless you want to return input argument, mis-using it as a glorified "for" loop)

And if returning not a list/dict, if you can use "min" or "max" or "any" or "all" or "next" (take the first element), then you should use it - it will be easier to read and faster too.

So what does this leave us for "reduce"? Frankly, not much. I've only seen it in merging immutable status codes, and that was pretty niche usecase to begin with.

(this was all for Python. In other languages without nice list of built-ins reduce might make more sense)

rsfern 1 day ago | parent

For numerical code I like einops.reduce more than numpy/pytorch sum reductions because you can reduce over named dimensions. It’s much more readable than having to reason through axis indexing again every time you come back to the code

Pinus 1 day ago | parent

Has the performance of sum on lists of lists in Python been fixed? It used to be pretty abysmal. But I suppose some would say that if you need to consider performance at all, you’re in the wrong language… :)

theamk 15 hours ago | parent

wow, TIL!

    Python 3.13.5 (main, Jul 15 2026, 20:25:40) [GCC 14.2.0] on linux
    >>> x = [[n]*1000 for n in range(1000)]; import timeit, itertools, functools, operator
    >>> timeit.timeit("len(list(sum(x, [])))", number=10, globals=globals())
    13.009033881127834
    >>> timeit.timeit("len(list(list(functools.reduce(operator.add, x, []))))", number=10, globals=globals())
    12.941937348805368
    >>> timeit.timeit("len(list(itertools.chain.from_iterable(x)))", number=10, globals=globals())
    0.0706032607704401
    >>> timeit.timeit("out=[]; [out.extend(i) for i in x]; len(out)", number=10, globals=globals())
    0.06334403157234192
    >>> timeit.timeit("len([i for a in x for i in a])", number=10, globals=globals())
    0.1232151910662651
mutable is fastest, itertools is just a bit slower, list comprehension is 2x slower, both "sum(..., [])" and "reduce" are 200 times slower!

evnix 1 day ago | parent

The name itself is confusing to begin with.

I come across reduce once in a few months, then I think it's a neat trick and a nice to have function.

then I forget it's even available and don't ever use unless these days LLM brings it up again.

karmakaze 1 day ago | parent

It's part of the functional trio: map, filter, reduce--and half of MapReduce.

billyp-rva 1 day ago | parent

Well yeah, it's the lowest-level array function. All of the others can be written with reduce, but not vice-versa. Of course it's going to be less friendly.

slopnt 1 day ago | parent

I like reduce in principle since it generalizes a simple concept pretty nicely. I don't use it that much in practice since its alternatives just require less brainpower. It competes against using local mutable state with a loop or iterator combinator which I would argue are easier to wrap your head around (i.e. loop with variable/map with closure). I would argue its one of those cases where something is just harder to do/understand in functional vs imperative programming.

g8oz 1 day ago | parent

I've always like reduce myself, didn't realize others had a negative attitude towards it.

japgolly 1 day ago | parent

I assume the author is talking about `fold`, as in `[A] -> B -> ((B,A) -> B) -> B`, and not what I often think of as reduce as `[A] -> ((A,A) -> A) -> A`.

`fold` is awesome and super useful. It's the easiest and most convenient way to turn a collection into a single value. Put me anecdotally in the opposite bucket.

wannabe44 47 minutes ago | parent

> `fold` is awesome and super useful. It's the easiest and most convenient way to turn a collection into a single value.

You will eventually learn about something called "for loop", and it will be nice.

t-3 43 minutes ago | parent

There are way more places where a simple typo will ruin you in a for loop than a reduce or fold or map. Using briefer abstractions in place of nested loops is almost always preferable.

mrkeen 34 minutes ago | parent

Nah. It involves multiple passes and setting the answer to the wrong value before (hopefully) setting it to the right value.

Plus it forces you out of whatever lazy/streaming paradigm you had going on. If your foldr produces a list, downstream can start consuming it in constant memory as long as you let it do its thing.

8note 27 minutes ago | parent

fold kinda does too, for setting the first combined value that you are assembling, and thus on an empty list you end up with that wrong value, same as the for loop

nightpool 6 minutes ago | parent

I think part of the issue is that a lot of programming languages don't make a strong distinction between the two, and only provide the (more powerful) fold, but in a way that makes reduce operations harder to reason about (like OP said, with 0 types).

Associativity also makes fold hard. It's not super trivial to know when you might need e.g. left fold vs right fold

s-zeng 1 day ago | parent

Even in the world of functional programming, there's an argument to be made that `fold` is a bit of a code smell, in a similar vein as `while` being slightly smelly in an imperative code base. There's good reasons for each to be used, but they are such low level iteration primitives that you might be better off with a higher one (e.g. for loops or iterators in imperative programs; in FP you might reach for monoidic reduces (as opposed to folds where the accumulator is a different type from the list element), monadic traverses, or recursion schemes). Even though you can implement iterators or for loops in terms of while loops, you probably shouldn't, and similar for functional traversals.

In languages like python or Java though, you don't really have access to many of the higher power functional traversals however. So that puts you into a similar kind of bind as working in a language with only while loops

snackbroken 1 day ago | parent

Map and Filter are nice because they let you reason locally about a single element in isolation. Reduce(Fold) forces you to reason globally about intermediate results. Reduce also forces you to conjure up a "zero" value of the relevant type, which isn't usually difficult but it does constitute some extra mental overhead.

mrkeen 40 minutes ago | parent

It's pairwise, not global reasoning.

snackbroken 14 minutes ago | parent

The accumulator is global state. If you're folding from list<int> to int you're right that it's (usually) effectively a pairwise operation on ints. If the fold is something like list<foo> -> tree<bar> then you have to reason about each intermediate (tree<bar>, foo) -> tree<bar>, i.e. how global state should evolve over time with each update.

chubot 38 minutes ago | parent

Related to the point about worse performance, I'm pretty sure I was there when reduce was "banished" from Python 3 -- demoted to functools.reduce(), instead of the builtin reduce() in Python 2

The story is that sometime in 2006 or 2007, Guido van Rossum was debugging why a web page in Google's internal code review tool (which he wrote) was taking 30+ seconds to render.

This is basically a "production" incident, since thousands of Google engineers relied on the tool. Requests like this were probably tying up threads and exhausting thread pools, perhaps

Eventually it was tracked down to a line wrapping algorithm written with reduce(). I don't think he wrote it -- it may have come in through a dependency. As many know, reduce() is basically:

     s1 + s2
     s1 + s2 + s3
     s1 + s2 + s3 + s4 
     ...
And that's O(n^2) when s_i are strings. And I think it showed up if you viewed a 5000+ line diff, or a 5000+ line file. (Newer programs like Github also suffer here)

I believe, in Python at that time, += was already optimized to avoid this (just like essentially all JS VMs are). Or you can use the idiom of append() to list and join() after.

But reduce() basically forces the inefficient implementation, and I'm sure this is still true in Python 3.

---

So basically Guido spent a long time debugging a performance problem related to reduce(), and made the decision to eject it, to help users avoid "footguns". I was his officemate at the time, so I recall this, but I wasn't involved directly

Also, somebody contributed reduce() to Python way back in the 90's, as well as other functional idioms. He wouldn't have added that himself -- it was never his preferred style.

He preferred a more imperative style. But he allowed those contributions, and then slightly regretted it later.

https://docs.python.org/3/library/functools.html#functools.r...

taeric 26 minutes ago | parent

This always feels odd to me. It would seem a fairly straight forward optimization of the interpreter to special case the different types that it can reduce.

That is, why couldn't they have done the essentially same trick that you reference for += with reduce?

kelipso 19 minutes ago | parent

I think many people don’t want to say this publicly but Python developers are really not the smartest of the bunch.

justonceokay 16 minutes ago | parent

That sounds nice but in practice it’s probably not super helpful. Yes you could make a special case for reducing “+” over integers. But in python you can generally not promise that all the inputs are strictly integers, and you can’t even promise that your “+” function has no side effects.

bmandale 15 minutes ago | parent

There is no such trick. Python is only now getting those sort of JIT style optimizations, and that one in particular still hasn't hit. Do not use += on strings in a loop unless you are certain the iteration count will be small.

There is an optimization for lists, and maybe that's what GP is remembering. l += is functionally different from l = l +. The former mutates l, whereas the latter creates a new l. The difference matters when the line above is m = l. The mutation version will mutate m as well (they're the same reference), the creates new version will not. This optimization can just as easily turn into a footgun if the programmer is unaware of it, and in that sense is unpythonic.

bjourne 8 minutes ago | parent

Maybe you are misremembering the story? += deferred concatenation requires lazy strings and that didn't come until 10-15 years later. However, concatenating string lists with sum() was a common Python idiom at the time and it indeed incurred O(n^2) complexity. Gvr's reduce dislike was more about its syntax. It doesn't mesh well with Python's lambda syntax.

semiinfinitely 36 minutes ago | parent

you guys still reading and review code with ur eyes and brain?

ChrisMarshallNY 30 minutes ago | parent

I like it, but I don't use it anywhere near as much as other built-in closures.

I find the two ways that you call it to be a bit annoying (not a showstopper). It just seems a bit "kludgy" to me.

sumolessons 26 minutes ago | parent

I wanted to add that from personal experience tastes can change! I didn't like reduce when I was first exposed to functional programming, but have come to prefer it.

Might be nonsensical, but one thing I sometimes wonder is why I reach for reducing a list to a value more often than I need to generate a list from a starting value. I guess the asymmetry has something to do with the kinds of applications I work on.

norir 24 minutes ago | parent

Anywhere that I could use reduce, I instead write a tail recursive function. This is also why I do not and will not ever choose python or javascript voluntarily.

juancn 23 minutes ago | parent

I like it conceptually, but the main issue for me with reduce is that it's hard to know exactly how the reduction will actually be executed.

The FUBAR potential with map and filter is much smaller, with reduce it depends on deep knowledge of the internals of the reduction itself.

yakshaving_jgt 21 minutes ago | parent

Monoids are not a difficult concept. Programmers should just learn a bit more.

WesolyKubeczek 19 minutes ago | parent

I like neither of the three and prefer for loops and if statements instead. Yay for shallower stacks!

Glyptodon 14 minutes ago | parent

It's on my list of things that are awkwardly named because there's not a great name to choose, particularly given how wide the different use cases are.

franey 14 minutes ago | parent

At least in TypeScript, it's a bit clunky to type, and I usually forget the order of the reduce function's arguments (accumulator, current item). Maybe it's just me, but it's especially easy to forget the order when the position of the accumulator is the 1st argument to the callback but the 2nd argument of the reduce function:

    array.reduce(
      (accumulator, currentItem) => {...},
      initialValue,
    )
In .filter(), The current item is the 1st argument and the intermediate/accumulated value comes later: filter((currentItem, index, intermediateArray)) => ...)

I use .filter() more often, so that argument ordering where currentItem is right next to the array is more intuitive for me