pass function as parameter in python


Salvador Dali:

Suppose I want to calculate the following f(f(...f(x)..).
Basically, many functions themselves.
Currently, I am doing the following to achieve this result (and return all intermediate steps):

def iterator(function, x, n=4):
    x = float(x)
    arr = []
    for i in range(n + 1):
        arr.append(x)
        x = function(x)

    return arr

def funcM(x):
    return x / 4 + 12

Then pass the function as funcMa parameter :
print iterator(funcM, 100, 5).

There is nothing wrong with this approach, the calculation is correct.

However, is there a way to do it without defining the function funcM?
Possibly passing a lambda function as a parameter to an iterator function (sorry if it doesn't make sense, I don't really know what a lambda function is).

Max Noel:

A lambda function (or more precisely, a lambda expression ) is just a function that you can define on the spot where you need it. E.g,

f = lambda x: x * 2

exactly the same as

def f(x):
    return x * 2

When I say exactly, I mean it - they disassemble to the same bytecode. The only difference between the two is that the names defined in the second example have names.

Lambda expressions become useful because creating a not statement means, as others have already answered, you can do

print iterator(lambda x: x / 4 + 12, 100, 5)

get what you want.

However, the main difference between lambda expressions and regular functions is that lambdas are more restricted. Lambdas can only contain expressions , not statements. An expression is anything you can put on the right side of an =assignment . (If you want more knowledge, Python defines expressions as http://docs.python.org/2/reference/expressions.html )

This means that a lambda expression cannot be assigned to a variable (in fact, it cannot contain local variables at all, except for parameters). It cannot print (unless another function is called to print). It cannot have for loops, while loops, if tests (except for the ternary operator x if cond else y) or try/except blocks.

If you need to do any of these operations, just define a regular function. In fact, anytime you want to use a lambda, think twice. Is the code more readable if using regular functions? Isn't that a lambda expression you want to reuse elsewhere in your code?

In the end, always do what results in the most readable and maintainable code. In terms of performance, there is no difference between a lambda and a regular function.

Related


pass function as parameter in python

Salvador Dali: Suppose I want to calculate the following f(f(...f(x)..). Basically, many functions themselves. Currently, I am doing the following to achieve this result (and return all intermediate steps): def iterator(function, x, n=4): x = float(x)

pass function as parameter in python

Salvador Dali: Suppose I want to calculate the following f(f(...f(x)..). Basically, many functions themselves. Currently, I am doing the following to achieve this result (and return all intermediate steps): def iterator(function, x, n=4): x = float(x)

pass function as parameter in python

Salvador Dali Suppose I want to calculate the following f(f(...f(x)..). Basically, many functions themselves. Currently, I am doing the following to achieve this result (and return all intermediate steps): def iterator(function, x, n=4): x = float(x) a

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Pass formula as function parameter in python

Simon I want to pass a formula in a function parameter in Python, where the formula is a combination of other function parameters. In principle it looks like this: myfunction(x=2,y=2,z=1,formula="x+2*y/z") 6 or more generally: def myformula(x,y,z,formula):

Pass formula as function parameter in python

Simon I want to pass a formula in a function parameter in Python, where the formula is a combination of other function parameters. In principle, this looks like this: myfunction(x=2,y=2,z=1,formula="x+2*y/z") 6 or more generally: def myformula(x,y,z,formula):

python pass request parameter to function

Badmiral I have a function def doStuff(): thing = str(request.args.get('thing')) return thing I want to call it from a script with parameters 'foo'. How can I do this? username def doStuff(bar): thing = str(bar) return thing doStuff('foo')

python pass variable to function parameter

critical application I think this is a python beginner's question. My goal is to pass a variable ( idx) to a function given as a parameter. I'm trying to wrap a function call to pass a variable as a parameter, but for some reason the result is not what I expec

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Pass image as parameter to function in python

Mujtaba Faizi How can I create a function that uses an image file (instead of the image file name) in python. In simple terms, it looks like this: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.im

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Python: pass tuple as parameter in function

ilovewt I am creating new column for Pandas DataFrameusing np.select(condition, choices). I want to modularize my code into a function, the cumbersome way of doing this is as follows: def selection( df: pd.DataFrame, conditions: Optional[List] = None,

Pass formula as function parameter in python

Simon I want to pass a formula in a function parameter in Python, where the formula is a combination of other function parameters. In principle, this looks like this: myfunction(x=2,y=2,z=1,formula="x+2*y/z") 6 or more generally: def myformula(x,y,z,formula):

python pass request parameter to function

Badmiral I have a function def doStuff(): thing = str(request.args.get('thing')) return thing I want to call it from a script with parameters 'foo'. How can I do this? username def doStuff(bar): thing = str(bar) return thing doStuff('foo')

Pass column as parameter in python function

Phuket (Pulkit Jha) I've been trying to use the code below to store unqiue values in a column in a pandas dataframe for further use in a function. Code snippet: def mergeFields(data,field): oldlist = pd.unique(data[field]) data_rcvd_from_satish.tags = me

python pass variable to function parameter

critical application I think this is a python beginner's question. My goal is to pass a variable ( idx) to a function given as a parameter. I'm trying to wrap a function call to pass a variable as a parameter, but for some reason the result is not what I expec

How to pass a function as a function parameter in Python

ba_ul 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 iterative equation on line 5

pass function as parameter in other function python

Mitas I have these functions, I am getting an error when using the do_twice function, but I am having trouble debugging #!/usr/bin/python #functins exercise 3.4 def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_twice

How to pass a function as a function parameter in Python

ba_ul 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 iterative equation on line 5

How to pass empty parameter to python function?

A generation Here is the working code: def g(y=10): return y**2 def f(x,y=10): return x*g(y) print(f(5)) #->500 However, let's say we don't want to remember and copy the default values of keyword arguments yinto the definition of the outer function

Pass variable value as parameter to python function

Gidon I am trying to pass a variable value as a parameter to a function used in a for loop. When I somehow call the function while printing the variable value, they display fine, but since I put Index out of range: 0 means nothing was passed to the function, w