xxxxxxxxxx
'''
Lambda functions are small functions that are very useful.
They take in as many attributes but only have 1 expression and you only
need 1 line to create them.
'''
# Writing a normal function
def add(a, b):
return a + b
# Writing a lambda function
add = lambda a, b: a + b
# You can use lambda functions as anonymous functions inside functions
def multiplier(n):
return lambda a: a * n
my_doubler = multiplier(2)
print(my_doubler(4)) # 8
print(my_doupler(5)) # 10
xxxxxxxxxx
lambda expression in C#
(param1, param2) => {return param1 + param2};
instead of typing
public int Add(param1, param2)
{
return para1 + param2;
}
and it usually used with delegates and LinQ statements
We have to specify function names while creating them. However, there is a special class of functions for which we do not need to specify function names.
Definition
A lambda is an anonymous function that returns some form of data.
Lambdas are defined using the lambda keyword. Since they return data, it is a good practice to assign them to a variable.
Syntax#
The following syntax is used for creating lambdas:
svg viewer
In the structure above, the parameters are optional.
Let’s try creating a few simple lambdas.
Below, we can find a lambda that triples the value of the parameter and returns this new value:
xxxxxxxxxx
triple = lambda num : num * 3 # Assigning the lambda to a variable
print(triple(10)) # Calling the lambda and giving it a parameter
xxxxxxxxxx
lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if condition is False>