Wednesday, December 14, 2011

Use of Lambda, Map, Reduce and Filter in Python


I have heard a lot about Lambda on Python.

I was scared in the beginning as I thought the code was very cryptic until very recently explored what it is all about.

Lambda is a anonymous function that one can write for quick operations instead of formally writing a function using def.

It can be used in conjunction with other functionality like Map, Reduce, Filter in Python.

Examples of Lambda are given below.

Map, Reduce and Filter functions in Python make writing code much more easier (less lines of code) and I think they are optimized internally which will make them more faster than writing custom code which will most probably be sub-optimal in terms of performance.

Here is a example of Matrix Multiplication (along with other optimizations) making use of Map along with some.

Now lets see what Map, Reduce, Filter is and how Lambda can be used with them.

  • Map functionality in Python i.e. with Syntax map(function, sequence) takes a sequence of values and passes it to function and returns a list of items.
  • Filter functionality in Python i.e. with Syntax filter(function, sequence) takes a sequence of values and passes it to function and returns a list of items for which function(item) is true.
  • Reduce functionality in Python i.e. with Syntax reduce(function, sequence) takes first 2 items in sequence, processes them and takes result, next item and so on.


No comments:

Post a Comment