Skip to content
Advertisement

How do you pass a function as an argument to another function, but the initial function’s arguments change?

How can you write a function f that takes another function g as an argument, but where function g has arguments that change dynamically depending on what happens in function f?

A pseudocode example would be:

def function(another_function(parameters)):  # another function passed as an argument, with parameters
    for i in range(10):
        print(another_function(i))

So when i iterates, function f is called with a new argument i every time. How could that be implemented?

I found one can use *args as a parameter, but did not see how it could be implemented.

Cheers

Advertisement

Answer

Let’s create a function that takes two parameters. The first parameter is a reference to a function and the other is a parameter to be used by that function

def func1(func, p):
    func(p)

func1(print, 'Hello world!')

So we call func1 with a reference to the built-in print function (doesn’t have to be built-in – could be any function that’s in scope)

Output:

Hello world!
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement