Lambda functions are anonymous functions which does not specify the function name when we print them.
Functions that we discussed in last sessions are defined using 'def' keyword however Lambda functions are defined using lambda keyword.
Lambda functions are not meant to write complex programs which can be done using normal functions.
Lambda functions can take any number of arguments, but can only have one expression.
<function bigger at 0x0000024658373A60>
We created above function 'bigger' & printed it but not performed function call. We can notice that function name is returned as output which is stored at some address. Do not compare this value with the memory address returned using id( ) function. id() of bigger is different.
2395082532616 <class 'function'>
Function to print number * 10
Using Lambda Function:
Lambda functions are defined as- Variable name = name of function i.e. lambda, then arguments, colon and expression. As shown below:
<function multiply at 0x0000022DA60B2CA8> <class 'function'>
<function <lambda> at 0x0000022DA60B2F78> <class 'function'>
In above examples, both functions belong to class 'function' however it can be seen that when we printed 'multiply' function, it has printed function name i.e. multiply.
But when we printed 'mult' function, it has not printed the function name. Hence, Lambda functions can be called as anonymous functions.
Let us try using 3 arguments in lambda function.
Notice that there are multiple arguments but only one expression.
Above program can be written as:
Create a lambda function to reverse a string.
To print value within the lambda function.
Can we use if-else condition within a lambda function?
How to use if-elif-else condition in Lambda function.
Direct elif does not work but below method is an alternative to it.
Expanding it more:
You are FIT
Return a lambda function from a regular function.
<function mult at 0x0000022DA60D50D8>
<function mult.<locals>.<lambda> at 0x0000022DA60EA3A8>
In above code, mult is a regular function however lambda function-> multiply is created as an instance of mult. Therefore, in output "function mult.locals.lambda" is written which means this lambda function will always point to mult function
Function that checks if given string is palindrome or not using lambda.
Its not a palindrome