Python lambda functions:
An anonymous function in Python is one that is defined without a name.
In Python, normal functions are defined with the def keyword, while anonymous functions are defined with the lambda keyword.
As a result, anonymous functions are also known as lambda functions.
Syntax:
lambda arguments: Expression
Lambda functions can take any number of arguments but can only execute one expression. The expression is evaluated and the result is returned. Lambda functions can be used in any situation where function objects are required.
Lambda with if but without else in Python
Example1:
Here we are printing the cube value of 3.
cubes = lambda a: a*a*a print(cubes (3))
Output:
27
Lamba function with only if statement
# Create a lambda function say mod_val which returns the given number # if the given number is greater than 0 mod_val = lambda k: k if(k > 0) # Pass some random number to the above lambda function and print the result print(mod_val(2))
Output:
File "<ipython-input-5-0f32857d7ac2>", line 3 mod_val = lambda k: k if(k > 0) ^ SyntaxError: invalid syntax
Explanation:
Here, it throws a syntax error, since a lambda function must return a value, and this function returns k if k> 0 and does not specify what will be returned if k is 0 or negative.
To solve this problem we should give the else part which returns if k is non-positive.
Example3:
Here it returns a given number since -k i.e, -(-2) = 2
# Lambda Function with if-else statements # Create a lambda function say mod_val which returns the given number # if the given number is greater than 0 mod_val = lambda k: k if(k > 0) else -k # Pass some random number to the above lambda function and print the result print(mod_val(-2))
Output:
2
Lambda Function with if-else statements
Here it returns the given number if the given number is greater than 0 else it prints None
# Lambda Function with if-else statements # Create a lambda function say mod_val which returns the given number # if the given number is greater than 0 else it prints None mod_val = lambda k: k if(k > 0) else None # Pass some random number to the above lambda function and print the result print(mod_val(2))
Output:
2
Lambda Function with map() function
Python’s map() function accepts a function and a list.
The function is called with all of the list’s items, and a new list is returned with items returned by that function for each item.
# Give the list as static input and store it in a variable. gvn_lst = [3, 5, 1, 2] # Adding 2 to each element of the given list using the lambda(), map() functions rslt_lst = list(map(lambda k: k + 2 , gvn_lst)) # Print the result list after adding 2 to each element of the given list print(rslt_lst)
Output:
[5, 7, 3, 4]