Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a function parameter in Python

This is what I currently have and it works fine:

def iterate(seed, num):
    x = seed
    orbit = [x]
    for i in range(num):
        x = 2 * x * (1 - x)
        orbit.append(x)
    return orbit

Now if I want to change the iterating equation on line 5 to, say, x = x ** 2 - 3, I'll have to create a new function with all the same code except line 5. How do I create a more general function that can have a function as a parameter?

like image 929
ba_ul Avatar asked Mar 01 '15 16:03

ba_ul


People also ask

Can you pass a function as a parameter in Python?

Functions can be passed around in Python. In fact there are functions built into Python that expect functions to be given as one or more of their arguments so that they can then call them later.

How do you parameter a function in Python?

Defining a FunctionFunction blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

Can you pass a function as a parameter?

Passing a function as parameter to another functionC++ has two ways to pass a function as a parameter. As you see, you can use either operation() or operation2() to give the same result.

Can we use a function as a parameter of another function?

You can use function handles as input arguments to other functions, which are called function functions. These functions evaluate mathematical expressions over a range of values.


2 Answers

Functions are first-class citizens in Python. you can pass a function as a parameter:

def iterate(seed, num, fct):
#                      ^^^
    x = seed
    orbit = [x]
    for i in range(num):
        x = fct(x)
        #   ^^^
        orbit.append(x)
    return orbit

In your code, you will pass the function you need as the third argument:

def f(x):
    return 2*x*(1-x)

iterate(seed, num, f)
#                  ^

Or

def g(x):
    return 3*x*(2-x)

iterate(seed, num, g)
#                  ^

Or ...


If you don't want to name a new function each time, you will have the option to pass an anonymous function (i.e.: lambda) instead:

iterate(seed, num, lambda x: 3*x*(4-x))
like image 169
Sylvain Leroux Avatar answered Oct 04 '22 19:10

Sylvain Leroux


Just pass the function as a parameter. For instance:

def iterate(seed, num, func=lambda x: 2*x*(1-x)):
    x = seed
    orbit = [x]
    for i in range(num):
        x = func(x)
        orbit.append(x)
    return orbit

You can then either use it as you currently do or pass a function (that takes a single argument) eg:

iterate(3, 12, lambda x: x**2-3)

You can also pass existing (non lambda functions) in the same way:

def newFunc(x):
    return x**2 - 3

iterate(3, 12, newFunc)
like image 23
Holloway Avatar answered Oct 04 '22 18:10

Holloway