How to make a list comprehension iterate a function

We want a list comprehension to iterate a function, for example this is what we want:

list2 = [f(f(f(...n f's...))) for n in list1]

I tried this code. As expected, it didn’t work.

How would this be possible?

>Solution :

Write a function that calls a function n times. Then call that in the list comprehension.

def call_n(func, n, arg):
    res = arg
    for _ in range(n):
        res = func(res)
    return res

list2 = [call_n(f, i, initial_value) for i in list1]

Leave a Reply