Map, Filter and Reduce in Python

Vivek Nikam and Abhay Chaudhari
3 min readJun 22, 2021

--

smart and simple

Photo by Sigmund on Unsplash

I hope you all are familiar with list, tuple, set, and dictionary in python.

In this article, we will see what is map, filter, and reduce in python.

Before that let’s see what is lambda function.

Normal function resides in memory for the lifetime of a program but what if we want to use a function for a single time, for that purpose there is a concept known as a lambda function.

It is a single line function and after execution, it gets deleted automatically from RAM. That’s why it is also known as an anonymous function.

let’s see normal function vs lambda function.

________________________________________________________________

Let’s see how we can use the lambda function in map, filter, and reduce.

map:

Map applies a function to all the items in a given iterable object.

It is a one-to-one relation.

syntax : map( function, iterable object )

Suppose, We have a list A= [ 2,3,6,7,8] and we want to create a new list that will have a square of numbers from list A.

In such a situation, we can use the map function.

here we have used a lambda function to calculate the square of a number. This function iterates over each element in A.

________________________________________________________________

filter:

Filter creates a list of elements for which a function returns true.

syntax : filter( function, iterable object )

always remember when there is a situation where we want m outputs from n inputs where m ≤ n, in that case, we can use the filter function.

As the name suggests, it filters the values.

Suppose, we want values from A which are even.

If a value is True then and then it will be added to the list.

________________________________________________________________

reduce:

reduce always returns a single value.

It is just a many-to-one relation.

First, we have to import reduce module from functools.

syntax : reduce( function, iterable object )

Let’s see how we can use reduce to calculate the sum of all elements in a list.

try to calculate the maximum element from a list using reduce function.

________________________________________________________________

This is how we can use these functions to save time while coding.

Thanks for reading!!!

--

--

No responses yet