What is Lambda function in Python? | applied electronics engineering


What is Lambda function in Python?

By Applied Electronics - Sunday, May 22, 2016 No Comments
Lamdda function in Python is a way of specifying a function using inline expression. Lamdda function are created using the reserved keyword lamdda followed by couple of arguments, then a colon and an expression with the argument after the colon. Lambda functions are also called anonymous functions and is alternative way of implementing python function. The name lambda comes from the LISP programming language.

The syntax of lambda function is given below:

lambda arg1, arg2 .. : expression using argument.

For example,

>>> f = lambda x, y: x+y
>>> f(2,3)

where, x and y are the arguments and x+y is the expression.
lambda function
 The expression x+y is like the return statement. Lambda function can take any number of input argument but returns only one value. Lambda function are called anonymous because they can be used anywhere in a python program with names that exist only within a certain boundary where it is defined, for example within a list or dictionary. There is a single expression and there is no block of statement in lambda function. That is lambda function cannot contain multiple statements. This makes lambda function different from ordinary function which uses def. Lambda functions are used when simple function code are sufficient. It is a shorthand for the def functions. 

 In the above example of using lambda function, we have used a name 'f' to the lambda function. But there are places where one is not tied to naming the lambda function like this. That is lambda function can be used anywhere because it is an expression and not statement.

>>> greater = (lambda x, y: x if x > y else y)
>>> greater(5,7)

Next we will see how lambda functions can be used together for Python Functional programming with map, filter and reduce.

No Comment to " What is Lambda function in Python? "