Tuesday, June 21, 2011

Lambda, map, filter and reduce

lambda

Python supports functions that are not bound to a name.we can use a construct called "lambda" for this. It can be used with functions like filter(), map() and reduce().

The general syntax of a lambda function is quite simple:
lambda argument_list: expression

For example:

>>> value=lambda x:x*x
>>> value(7)
49

More than one arguments are supported and these are separated by comma.The expression is an arithmetic expression using these arguments.

For example:

>>> value=lambda x,y:x/y
>>> value(47,5)
9

map()

map() is a function with two arguments:
r = map(func, seq)
The first argument func is the name of a function.Second argument is a sequence like list.
map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func.

>>> value=[1,4,7,5,8]
>>> def sqrt(x):
... return x*x
>>> map(sqrt,value)
[1, 16, 49, 25, 64]

The advantage of the lambda operator can be seen when it is used in combination with the map() function.

>>> a=[5,6,4,8]
>>> b=[4,3,2,7]
>>> map(lambda x,y:x*y, a,b)
[20, 18, 8, 56]


filter()

This function is used to filter out all the elements of a list.

filter(fun, list)

The first argument, fun needs a function which returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. If the fun returns true for a particular element of the list,that will be included in the result list.

>>> a=[4,5,76,34,7,32,45,89]
>>> result = filter(lambda x: x % 2, a)
>>> print result
[5, 7, 45, 89]

reduce()

The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.

Suppose seq = [ s1, s2, s3, ... , sn ].When we call reduce(func, seq) , first 2 elements of the seq will be applied to func at first.In the next step func will be applied on the previous result and the third element of the list.It will continue like this until just one element is left and return this element as the result of reduce() .

>>> reduce(lambda x,y:x+y,[34,78,435,23,78])
648



1 comment: