0

Suppose I have a complicated function function f(A, B) . I want to recursively apply this to a list of inputs, X = [C, D, E].

I would like to know how I can define a function g so that the output of g([C, D, E]) is f(f(C, D), E), for arbitrary lengths of X.

Let us define an example function:

def f(A, B):
    return A + B

How would I define g?

Jack Rolph
  • 587
  • 5
  • 15

1 Answers1

1

There is reduce that does that:

from functools import reduce
result = reduce(f, [1, 2, 3])

If you prefer to define it yourself:

def g(lst):
    res = lst[0]
    for val in lst[1:]:
        res = f(res, val)
    return res

result = g([1, 2, 3])

If you want to get just one argument using reduce, then embed it as follows:

g = lambda lst: reduce(f, lst)
trincot
  • 317,000
  • 35
  • 244
  • 286