Lambda inside higher-order functions
One main use of a lambda function is as an anonymous function inside another function.
For example, we might have a multiplier function that takes a number n as input, and returns a function that takes another number x as input and multiplies x by n (that was quite a mouthful!)
def multiplier(n):
return lambda x: x * n
And we can have a variable doubler that is set to double a number. Remember, multipler(2) returns a function, and so doubler basically points to a function!
doubler = multiplier(2)
We can then call doubler to double a number.
print(doubler(5)) ## 10
Similarly, we can create another function called tripler and call it with another number to triple the number.
tripler = multiplier(3)
print(tripler(4)) ## 12
In the next few pages, we will look at some Python built-in higher order functions that can be used with lambda functions. Higher order functions are functions that take a function as an input argument, or that return a function.
Try to make sure that you understand these examples before moving on. Otherwise the next few pages might actually be even more confusing! 😕
[Credit: These examples are taken from the fantastic w3schools.com]