Map, Filter & Reduce

  • Python

Map(), Filter(), and Reduce() are built-in python functions that provide a functional programming approach to your code. In this article, we’ll learn about syntax of all these functions and how to use them.

Map

Map function is used when we need to apply a function to a list of elements. In this, all the values in the list will be passed to the function as a parameter.

Syntax of map is –

map(function_to_apply, iterable)

function_to_apply means the function that we’ll be using to iterate over the values in the given list. Let’s understand this with an example where we require the square of the numbers.

def sq(a):
  return a**2

nums = [1,2,3,4,5]
square = list(map(sq, nums))

print(square)

Output :

[1, 4, 9, 16, 25]

In the above example, we created a function called sq that returns the square of the input values and passed it to the map() function. Now, there will be situations where the function will be used only once. In this situation, lambda functions will come to the rescue.

nums = [1,2,3,4,5]
square = list(map(lambda a : a**2, nums))
print(square)

Output :

[1, 4, 9, 16, 25]

Filter

Filter, as the name suggests it will filter values from the given list using the given function. Just like map(), filter() also requires a function and an iterable.

Syntax of filter is same –

map(function_to_apply, iterable)

Let’s use the previous example and return only the even values.

nums = [1,2,3,4,5]
evens = list(filter(lambda a : a%2==0, nums))
print(evens)

Output :

[2, 4]

Reduce

While map() applies a function to a list, filter() filters out the values as per the function, reduce() on the other hand, returns a single value.

Also, in python 3, reduce() is no longer a built-in function and has to be imported from functools. Let’s understand with an example where you need to add all the numbers in the list or want a product of all numbers in a list.

from functools import reduce

nums = [1, 2, 3, 4, 5]

product = reduce((lambda x, y: x * y), nums)
print(product)

sums = reduce((lambda x,y: x + y), nums)
print(sums)

Output :

120
15

Like mentioned, reduce returns a single value.