Recent Posts

Lambda function in Python

What is lambda ?

Lambda is a kind of function which is similar to def  function but not like at all. Lambda should have one line statement but if you make a function with def then you can several lines of statement.

Like an example
>>> def func (x): return x**2      #Line 1 
... 
>>> print func(8)                          #Line 2
64
>>> 
>>> func = lambda x: x**2         # Line 3
>>> 
>>> print func(8)                         #Line 4 
64 

Here line 1, a function func is defined which take one parameter and return the square of it. You can write the program like 
def func(x):
... y = x**2
...  return y
 this. It work fine. In line 3 an instance of lambda function is made into func, in line 4 just send the number of argument which is defined into lambda x (lambda x) look here only one x,so one argument). Lambda function only have a return statement, you can't write it like multiple statement.
If you want to subtract two element then write lambda function like subt = lambda x,y : x-y , then print(subt(5,7)). I send two argument because lambda x,y accept two.

Lambda can send tuple like function (i mean tuple by multiple result return) 

If you have any query then please comment :) 

Post a Comment

0 Comments