5.4. Lambda functions#
A lambda function, also known as an anonymous function is a small function consisting of a single expression. A lambda function is declared using
output = lambda arguments : expression
To demonstrate this lets declare lambda function to triple a number. Enter the following code into your program.
# Lambda functions
triple = lambda x : 3 * x
print()
print(triple(4))
Run your program and you should see the following added to the console.
12
5.4.1. Returning a lambda function#
Lambda functions can be used when we want to return a function from another function. For example, lets say that we want a function that multiples the input x
by some number k
. Enter the following into your program.
# Returning a lambda function
def multiply(k):
return lambda x : k * x
We can then use the multiply()
function to declare other functions to double, triple and quadruple the input. Enter the following into your program.
double = multiply(2)
triple = multiply(3)
quadruple = multiply(4)
print()
print(double(5))
print(triple(5))
print(quadruple(5))
Run your program and your should see the following added to the console.
10
15
20
5.4.2. Exercises#
Write a lambda function that calculates the value \(y\) using the following quadratic for different input values of \(x\)
Use your function to calculate \(y\) when:
\(x = 2\)
\(x = 3\)
Write a function called power_function()
that returns a function which raises an input \(x\) to the power \(n\). Use this function to create the following functions:
square()
that calculates \(x^2\)cube()
that calculates \(x^3\)quartic()
that calculates \(x^4\)
Use your functions to calculate the square, cube and quartic of 123.