0

Is there a shortcut in python for applying the same function multiple times to a variable (and its output)?

Something like:

# n times foo(x)

instead of

foo(foo(foo...(foo(x))))...)
1
  • A for loop is best for this. Commented May 16, 2012 at 5:43

3 Answers 3

6
for i in range(n):
    x = foo(x)

If you need to preserve x, use a different name

baz = x
for i in range(n):
    baz = foo(baz)

If you are desperate for a shortcut (eg. for codegolf)

reduce(lambda x,y:foo(x),[x]*n)
Sign up to request clarification or add additional context in comments.

1 Comment

the shortcut is too smart.
3
def double(x):
    return x * 2

i = 44
for i in xrange(1,100):
    i = double(i)

Could you mean a simple for loop?

Comments

1

One of the ways i can think of is creating a generic recursive function to do this

def repeatX(foo, output, count):
      if not count:
         return output
      else:
         return repeatX(foo, foo(output), count -1)

1 Comment

Unchecked recursion in python is pretty much always a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.