Viet Viet - 1 year ago 84
Python Question

Apply a list of Python functions in order elegantly

I have an input value

and a list of functions to be applied in the order:

funcs = [f1, f2, f3, ..., fn]

How to apply elegantly and not writing

fn( ... (f3(f2(f1(val))) ... )

and also not using for loop:

tmp = val
for f in funcs:
tmp = f(tmp)

Thanks Martijn for the awesome answer. There's some reading I found: .

Answer Source

Use the reduce() function:

# forward-compatible import
from functools import reduce

result = reduce(lambda res, f: f(res), funcs, val)

reduce() applies the first argument, a callable, to each element taken from the second argument, plus the accumulated result so far (as (result, element)). The third argument is a starting value (the first element from funcs would be used otherwise).

In Python 3, the built-in function was moved to the functools.reduce() location; for forward compatibility that same reference is available in Python 2.6 and up.

Other languages may call this folding.

If you need intermediate results for each function too, use itertools.accumulate() (only from Python 3.3 onwards for a version that takes a function argument):

from itertools import accumulate, chain
running_results = accumulate(chain(val, funcs), lambda res, f: f(res))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download