../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

< 3.4 Lambda Functions | Contents | 3.6 Summary and Problems >

Functions as Arguments to Functions

Up until now, you have assigned various data structures to variable names. Being able to assign a data structure to a variable allows us to pass information to functions and get information back from them in a neat and orderly way. Sometimes it is useful to be able to pass a function as a variable to another function. In other words, the input to some functions may be other functions. In last section, we did see the lambda function returns a function object to the variable. In this section, we will continue to see how the function object can be used as the input to another function.

TRY IT! Assign the function max to the variable f. Verify the type of f.

f = max
print(type(f))
<class 'builtin_function_or_method'>

In the previous example, f is now equivalent to the max function. Just like x = 1 means that x and 1 are interchangeable, f and max function are now interchangeable.

TRY IT! Get the maximum value from list [2, 3, 5] using f. Verify that the result is the same as using max.

print(f([2, 3, 5]))
print(max([2, 3, 5]))
5
5

TRY IT! Write a function my_fun_plus_one that takes a function object, f, and a float number x as input arguments. my_fun_plus_one should return f evaluated at x, and the result added to the value 1. Verify that it works for various functions and values of x.

import numpy as np 

def my_fun_plus_one(f, x):
    return f(x) + 1

print(my_fun_plus_one(np.sin, np.pi/2))
print(my_fun_plus_one(np.cos, np.pi/2))
print(my_fun_plus_one(np.sqrt, 25))
2.0
1.0
6.0

We can see the above example that different functions are used as the inputs into the function. Of course, we can use the lambda functions as well.

print(my_fun_plus_one(lambda x: x + 2, 2))
5

< 3.4 Lambda Functions | Contents | 3.6 Summary and Problems >