Getting Started With Map, Filter, and Reduce in Python


For example sure, at some point you will have to deal with each and every element of the list. A naive approach to do something with each element of a list is to use a for loop. In general, for loops are frowned upon and you should always look for ways to write code with one loop lesser. Thats where these functional constructs in Python come in extremely handy.

Map Function in Python

In the simplest form, the built-in function map takes in a function and a list as input and applies the function to each element of the list. As you can immediately see that, in this case map can replace a for loop. Let us consider an example of using the map function. Let us say we have a list of numbers like

>>>myList = range(10)

For each element in the list, if we want to compute a function f(x) (say 3*x^2)), where x is a list element and input to the function, the (one) pythonic way of getting this done is to avoid loops and write

>>>map(lambda x: 3*x**2, myList)
[0, 3, 12, 27, 48, 75, 108, 147, 192, 243]

Note that one can use any complex function that does something with the list elements and return a list of the same size.

Filter Function in Python

Filter function works very similar to the map function. Instead of just applying the function on all the elements in the list, filter function filters the elements based on the condition used in the lambda function.For example, if we want to find the even numbers in the list “myList”, the filter function will come handy.

>>>filter(lambda x: x%2==0, myList)
[0, 2, 4, 6, 8]

Reduce Function in Python

Reduce function in Python will come handy when you want to operate on a list and reduce to a single value. A simple example using the reduce function will be to use to find the sum of all the elements of a list, like

>>>>reduce(lambda x, y: x+y, myList)

Basically, reduce function adds the first two elements and adds the result to next element in the list till. Reduce does this till it is reduced to one value.

If you think, the map, filter, and reduce functions are cool, wait till you learn about List Comprehensions in Python.