Sunday, 14 February 2021

Python Lambda Expression

 


Anonyms Function the name itself says that we can define a function without a name, To define these functions we use Lambda function or Lambda Expression.

We define a function in python using def keyword followed by the name of that function.

like 



 

    In the above defined function we use def  keyword,  this keyword will tell python that  hey I am creating a new function which name is addition and it will take two Arguments such as a , b. These functions called as User defined function.

In case of Lambda Expression we use lambda keyword followed by  Arguments and then we define the action that we need to take on arguments. The syntax is as per mentioned in below image.




Lambda Expression always return function so we need to assign it to a variable, and we can use it multiple times.

ex:

                        lam_funct = lambda a, b : a + b


here lam_funct is a variable and we assign lambda expression to it. while printing we need to call that variable and pass the value of argument as we do in user defined functions.

lets go through some examples:

Addition:




same if need to perform multiplication in lam_funct you can change the arithmetic operator from "+" to "*" and you will get the multiplication for a and b.


To sort a given list of string, sort it using lambda expression




the above will print ['Nike', 'addidas', 'sparks']


lambda function is very useful when we use it inside other functions. we can use it with user defined function. Lets go to the above addition user defined function




if ........else statement using lambda function:

===================================

Odd and even find 






Some Programmers use anonymous functions just for matter of style. That is never the only way of solving problem

Post Top Ad

Your Ad Spot

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template