Thursday, December 17, 2015

How to use "lambda" in python ??

Few days ago, I came across a very interesting function used in one of the python test scripts. Its called "lambda"
lambda is like a callback function. Its a alternate to def in situations where 

  • function is just one liner & only used once
  • when a calling function needs a function as an input parameter
It is a keyword used to define "anonymous function". Its a kind of functionality similar to defining function where you define parameters and what to do with it.

But by using lambda, you can make use of other functions like "filter, map and reduce". I have provided this sample python script where lambda function is defined and shown how it can be used along with filter, map and reduce ...

#__author__ = 'Sumant'
# use of lambda function along with "filter, map & reduce"
xx = lambda a, b: a+b
print xx(2, 3)

lst = range(1, 6)
print "lst = " + str(lst)
print "filter functionality:"
print filter(lambda a: a+1 < 5, lst)
print "lst = " + str(lst)
print "maps functionality:"
print map(lambda a, b: a*b, lst, lst)
print "lst = " + str(lst)
print "reduce functionality:"
print reduce(lambda a, b: a * b, lst)

--------------------------------
OUTPUT
--------------------------------
5
lst = [1, 2, 3, 4, 5]
filter functionality:
[1, 2, 3]
lst = [1, 2, 3, 4, 5]
maps functionality:
[1, 4, 9, 16, 25]
lst = [1, 2, 3, 4, 5]
reduce functionality:
120

Process finished with exit code 0


Hope this link will be helpful ... :)

There are few very wonderful links where it is explained when & where to use "lambda" function:
https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/

No comments:

Post a Comment

PROFILE

My photo
India
Design Engineer ( IFM Engineering Private Limited )

Followers