Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading