Python — Map, Filter, Reduce

Chandan Sengupta
4 min readMar 6, 2023

--

MAP

First, let us understand why exactly we need a map function and how it helps us reduce our work and make our code more efficient.

Suppose we have a list to work on as below, but the problem with the list is, all the elements present in it are in string format, so if we try to perform any numerical operations, it will not yield any result.

l1 = ["3","5","9","12","25"]
x = l1[0]+1
print(x)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [1], in <cell line: 2>()
1 l1 = ["3","5","9","12","25"]
----> 2 x = l1[0]+1
3 print(x)
TypeError: can only concatenate str (not "int") to str

As we can see above, an error is thrown in the code stating that the object we are trying to perform our addition operation on is in str format and hence can not be the same. Here ‘x’ is the variable where we have stored the element of addition of an str value with int, that needs to be changed.

Now one way around this is a for loop, let us have a look

for i in range(len(l1)):
l1[i] = int(l1[i])

Now if we perform the same operation as we did earlier, it will not throw any errors. Let’s have a look.

x = l1[0]+1
print(x)
4

As the first element of the l1 list 3, so 1 got added with it and we have received 4 as the result. But this is not an ideal solution, as every time writing for loop doesn’t sound feasible, to avoid such issues we take the help of the map function, where a single line of code can solve our issue. let’s have a look

We’ll take another list called l2 and will perform the same operation again.

l2 = ["3","5","9","12","25"]
l2 = list(map(int,l2))
y = l2[0]+1
print(y)
4

As we can see, with the help of the map function it worked perfectly, always remember the kind of function we want to operate in our data type should always be the first argument inside the map function, in here we are trying to convert the str elements into an int, hence after map keyword we used the int argument as the first one.

Now let’s have a look at a few other examples as well, suppose we want to find out the square values of an entire list, let’s see how we can do that with the help of the map function.

First, let’s write a function ‘sq’ which will return the squared value of a given number

def sq(a):
return a*a

Now let’s create a list named l3 with integer elements

l3 = [3,5,7,2,9]
l4 = list(map(sq,l3))
print(l4)
[9, 25, 49, 4, 81]

As we can see, we are able to get the squared value for all the elements present in the list.

Now let’s look into something more complicated, what we are trying to achieve now is to get the square and cube of numbers from 0,8, stored in a list. We will use the map function, lambda function, and also our def keyword to describe the square and cube functions now. Then we will use a for loop to create the list.

def sq(a):
return a*a
def cube(a):
return a*a*a
func = [sq,cube]
for i in range(8):
rslt = list(map(lambda x:x(i) ,func))
print(rslt)
[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
[25, 125]
[36, 216]
[49, 343]

Filter

As the name suggests, the filter function helps us in filtering a given set of iterables , as an argument it takes the stated function based on which we will be filtering our iterables and then it takes the iterables themselves as the arguments. Below 3 types of filters are given, one will filter numbers greater than 10 from the list, one will filter numbers lesser than 10, and one will have multiple conditioning that states the number should be greater than 10 but lesser than 15.

l1 = [34,12,5,8,11,14,19,10,1,50]
def grt_condi(num):
return num>10
def lsr_condi(num):
return num<10
def multi_condi(num):
return num>10 and num<15

l2 = list(filter(grt_condi,l1))
l3 = list(filter(lsr_condi,l1))
l4 = list(filter(multi_condi,l1))

print(l2)
print(l3)
print(l4)
[34, 12, 11, 14, 19, 50]
[5, 8, 1]
[12, 11, 14]

Reduce

Let’s understand what reduce function does and what problem it solves, to understand this, let’s first take a problem statement and our traditional walkaround in solving that.

Let’s say there is a list and we want to get the summation of all the integers present in the list

l6 = [2,3,6,5,8,9,10]
x = 0
for i in l6:
x = x+i
print(x)
43

But again writing all these lines of code doesn’t seem so python like, let’s reduce our line of code and see what we can achieve here. and one more thing is that we need to import reduce function from functools first in order to proceed.

from functools import reduce
l7 = reduce(lambda x,y:x+y , l6)
print(l7)
43

I hope this article helped you to gain some insights into the Map, filter and reduce concepts in python.

For more such content please follow my Medium profile and LinkedIn page — https://www.linkedin.com/in/chandan-sengupta/

--

--