Functional ops on lists: where is FoldList?

David Eppstein eppstein at ics.uci.edu
Tue Jan 22 14:11:45 EST 2002


Python's reduce operation is very similar to Mathematica's Fold.
But I can't find anything similar to FoldList:
FoldList[f, x, {a, b, c, ... }] returns the list
    {x, f[x,a], f[f[x,a],b], f[f[f[x,a],b],c], ... }

If that's unclear, here's the simple-generator version of what I mean, with 
the "x" argument to FoldList dropped for consistency with reduce():

def reduceIter(f, It):
        x = It.next()
        while 1:
                yield x
                x = f(x, It.next())

def reduceList(f, L):
        return list(reduceIter(f, iter(L)))

I'm curious why this was omitted from Python's built-in 
functional-programming repertoire.

(This is a continuation of my efforts in using Python for my algorithms 
class -- today's lecture includes counting sort, and reduceList would have 
been useful for the part where you sum the counts of each symbol to produce 
output positions for each symbol. As it is, I will just do it in a loop, 
which will probably end up confusing the students less anyway.)
-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list