Lambda functions (anonymous functions) are used to perform a simple operation with a single line. Below are two ways of achieving the same result - one with a regular function, and the second one with a lambda function:
Here we define a lambda function and assign it to
add, after which
addacts as a regular function. In practice, it’s more common to pass lambda functions to other functions instead of assigning them. We’ll discuss those use cases soon.
The syntax for a lambda function is
lambdafollowed by the arguments without brackets
()followed by a colon
:and a return statement without a
We can have multiple arguments in a lambda function separated by a comma:
Pay attention that the lambda functions can only be written on a single line and cannot span several lines. They are meant for simple one-time computations.
You are asked to implement the following function with a lambda expression:
The lambda function should return the value of the function given two floating-point values -