Tuesday, 24 January 2017

LAMBDA FUNCTIONS IN PYTHON

A function which doesn’t contain any name explicitly is known as Lambda functions or Anonymous functions. Syntax –
Lambda arguments : expression
A lambda function can contain ‘n’ number or arguments. A lambda function can contain only one expression. After executing lambda function it will return the expression value.

Example –
a = lambda x : x*2
print a(5)
 
Output –
10
 
Note – The above lambda function is equal to the following code –
 
def a(x):
    return x*2
print a(5)
 
 
Note – Generally we use the lambda functions whenever we want to pass one 
function as parameter to another function.
 
 
Example – filter function
my_list=[1,2,3,5,6,8,9]
even_list=filter(lambda x : (x%2==0),my_list)
print even_list
odd_list=filter(lambda x : (x%2!=0),my_list)
print odd_list
 
Output –
[2, 6, 8]
[1, 3, 5, 9]

No comments:

Post a Comment