Python supports higher order functions, that is, functions that can accept other functions as arguments.
Let's leverage the square_input
function defined in the previous example and write a code snippet that will demonstrate how functions can be passed as parameters.
Let's now demonstrate how to pass a function as a parameter:
from math import log def square_input(x): return x*x # 1. Define a generic function, which will take another function as input # and will apply it on the given input sequence. def apply_func(func_x,input_x): return map(func_x,input_x) # Let us try to use the apply_func() and verify the results a = [2,3,4] print apply_func(square_input,a) print apply_func(log,a)
In step 1, we defined a apply_func
function with two variables. The first variable is a function and second one is a sequence. As you can see, we used the map function (more on this function in the recipes to follow) to apply the given function to all the elements of the sequence.
Next, we invoked apply_func
on a list a; first with the square_input
function followed by a log
function. The output is as follows:
[4, 9, 16]
As you can see, the elements of a are all squared. The map applies the square_input function to all the elements in the sequence:
[0.69314718055994529, 1.0986122886681098, 1.3862943611198906]
Similarly, log is applied on all the elements in the sequence.