Python lambda function is defined without a name. Instead, the anonymous functions are defined using a lambda keyword.
Syntax of Lambda function
lambda arguments: expression
The lambda functions can have any number of parameters but only one expression. That expression is evaluated and returned. Thus, lambda functions can be used wherever a function object is required.
cube = lambda x: x * x * x
print(cube(11))
Output
1331
Using if-else in the Lambda function
The if-else in lambda function syntax is the following.
lambda <arguments> : <Return Value if condition is True>
if <condition> else <Return Value if condition is False>
For example, let’s create the lambda function to check whether the given value is between 11 and 22.
verify = lambda x: True if (x > 11 and x < 22) else False
print(verify(15))
print(verify(22))
print(verify(21))
Output
True
False
True
15 is between 11 and 22, so it returns True.
22 is not less than 22. So it returns False.
21 is between 11 and 22. So it returns True.
Conditional lambda function without if-else
We can avoid using if & else keywords for Python lambda and still achieve the same results. For example, let’s modify the above-created lambda function by removing if-else keywords.
verify = lambda x : x > 11 and x < 22
print(verify(15))
print(verify(22))
print(verify(21))
Output
True
False
True
We got the same output, and you can see that we can write the conditions without if-else statements.
The lambda function does the same as the above checks if the given number lies between 10 and 20. Now let’s use this function to check some values.
Using if, elif & else in Python lambda function
lambda <args> : <return Value> if <condition > ( <return value >
if <condition> else <return value>)
Create a lambda function that accepts the number and returns a new number based on this logic,
- If the given value is less than 11, then return by multiplying it by 2.
- Else if it’s between 11 to 22, then return, multiplying it by 3.
- Else returns the same un-modified value.
converter = lambda x : x*2 if x < 11 else (x*3 if x < 22 else x)
print(converter(5))
print(converter(24))
Output
10
24
So, in the above example, 5 * 2 = 10, less than 11. So, it returns 10 because it satisfies the condition. But, in the case of 24, it does not satisfy any condition; that is why it returns 24 as it is.
That’s it.
Thanks for this post bro