Monday 31 March 2014

Python Function – lambda




Lambda is a single line anonymous function used in python.  The format is like below:

lambda parameters: expression
sample code
>>> (lambda x: x*x)(3)
9

paramters are where you put your parameter list and expression is the function expression you want to return.
Some points:

  • You don’t need to use () for the parameter list.
  • No explicit return statement
  • Lambda expression can be used as a function by (lambda) (parameters)

Here is another example
>>> Condition = True
>>> ObjectString = "my_email_address gmail.com"
>>> processFunc = Condition and (lambda s: "@".join(s.split())) or (lambda s: s)
>>> processFunc(ObjectString)
'my_email_address@gmail.com'
processFunc is actually a function with a Condition.
 
In real word, lambda is widely used with the build-in functions such as map, filter and reduce.  

Get the square of each element in the list

mylist = [1,3,5,7,9,0]
map( lambda x: x*x , mylist)
 

or it can be expressed in list comprehension
[ x*x for x in mylist]
 

Get all the element if the element is bigger than 0

mylist = [1,-2,3,-4,5,-6,7,-8]
Filter((lambda x: x> 0), mylist)


Dictionary sort

sorted(dict.items(), key=lambda e:e[1], reverse=True) – sort key by value
sorted(dict.items(), key=lambda e:e[0], reverse=True) – sort key by key

No comments:

Post a Comment