Let’s say there are two numbers and we want to find out the maximum of the two numbers. One way to do so is to use a simple function that takes two arguments a and b. If a > b, it returns a. Otherwise, it returns b.
Another option is to use a lambda function in Python. Using a lambda function, one can write a small piece of code that can be used for a short period of time.
For example,
Maximum = lambda a, b: a if a > b else b print(Maximum(2,3))
The syntax of a lambda function is:
lambda arguments: expression
So, in the above program, the lambda function takes two arguments a and b. Then, it evaluates the expression “a if a > b else b”. As a result, the lambda function will return the maximum of a and b. So, print(Maximum(2,3)) will print the following output:
3
A lambda function can also be used inside another function. Let’s say we want to write an incrementor function that increments a given number by a specific number. One way to do this is to write a small function that takes two arguments – n and i. Then, it increments n by i. Another option is to use a lambda function inside the increment function in the following way:
def increment(n): return lambda x: x + n
The lambda function takes x as an argument and increments x by n. So, now, we can define another function called increment_by_5 like the following:
0 Comments