How can I apply a function to itself?

Suppose I have function, f, which takes in some variable and returns a variable of the same type. For simplicity, let’s say

def f(x):
    return x/2+1

I’m interested in applying f to itself over and over. Something like f(f(f(...(f(x))...))).

I could do this like

s = f(x)
for i in range(100):
    s = f(s)

But I was wondering if there was a simpler, less verbose way to doing the same thing. I wan’t to avoid for loops (just as a challenge to myself). Is there maybe some way of using map or a similar function to accomplish this?

Solution:

Is there maybe some way of using map or a similar function to accomplish this?

Not map, but reduce. I wouldn’t use it for this, but you could call reduce on an n-item sequence to cause f to be called n times. For example:

>>> def f(x):
...   return x+1
... 
>>> reduce(lambda n,_: f(n), range(100), 42)
142

Explanation:

  • n is assigned each successive return value of f.
  • _ is the list of numbers from range(100). These numbers are all ignored. All that matters is how many there are.
  • 42 is the starting value.

100 nested calls to f(f(f...(f(42))...)) results in 142.