Can we Write For loop as a function?

You could do this, but you probably shouldn’t:

def forn(n):
    def new_func(func):
        for i in range(n):
        return func
    return new_func

def f(i):

or this:

def forn(n, func)
    return [func(i) for i in range(n)]

x = forn(10, lambda x: x**2)

But these are more verbose and less readable than

for i in range(10):


x = [i**2 for i in range(10)]

As others have said, you’ll do best to just use the built-in tools.

Browse More Popular Posts

Leave a Comment