Does Python have a `nest` function like Mathematica?

Viewed 108

Mathematica has a convenient Nest function for repeatedly evaluating f(f(f(f(...f(n))))). Not something you need every day, but occasionally useful. Here is a trivial implementation:

def nest(f, expr, n):
    assert n >= 0
    if n == 0:
        return expr
    else:
        return f(nest(f, expr, n - 1))
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676

Is there a Pythonic way to do this?

2 Answers

Perhaps if you like these sorts of things, you can look into functools.reduce:

from functools import reduce

def nest(f, expr, n):
    return reduce(lambda x, _: f(x), range(n), expr)
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676

Talking Pythonic, which is a bit of an opinion-based concept, I'd say a simple iterative implementation is more readable (Readability being a core Python principle) than reduce-based or recursive approaches:

def nest(f, expr, n):
    for _ in range(n):
        expr = f(expr)
    return expr

Certainly, I will not have to stare down what's happening here as much as in the other cases. If it is, however, brevity you're after, you can go with a conditional expression:

def nest(f, expr, n):
    return f(nest(f, expr, n - 1)) if n else expr
Related