Take the 2-minute tour ×

I want a function named times(), in order to make:

times(func,2) equivalent to lambda x:func(func(x))

and times(func,5) equivalent to lambda x:func(func(func(func(func(x)))))

Is there such a tool in Python? What would the code looks like if I want to write it by myself?


share|improve this question
add comment

2 Answers

up vote 15 down vote accepted

I'd suggest to call this power(), since this is actually the nth power of a function. There is no such thing in the standard library, but you can easily implement it yourself:

def power(f, n):
    def wrapped(x):
        for i in range(n):
            x = f(x)
        return x
    return wrapped
share|improve this answer
Thanks, Sven. The wrapped function looks magic. –  Firegun Jul 20 '12 at 23:52
I would give this +100 if I could. So elegant! –  inspectorG4dget Jul 20 '12 at 23:58
I'm just wondering whether there's a recursive instead of iterative way to do this.. –  Firegun Jul 21 '12 at 0:03
add comment

Thanks, Sven

I found a recursive way to do that, but yours looks more pythonic:

def power(func, n):
    def lazy(x, i=n):
        return func(lazy(x, i-1)) if i > 0 else x
    return lazy    

>>> power(lambda x:x*2,3)(9)
>>> power(lambda x:x*2,2)(9)
>>> power(lambda x:x*2,1)(9)
>>> power(lambda x:x*2,0)(9)

And a way implemented with decorator:

def powerize(n):
    def wrapped(func):
        def newfunc(*args):
            return power(func,n)(*args)
        return newfunc
    return wrapped

def double_3(x):
    return x*2

>>> double_3(8)
share|improve this answer
add comment

Your Answer


