Filter Map and Reduce Functions In Python

avatar

image.png

Image Source

In my previous post, I have discussed about Lambda functions in python and in this post, I am gonna talk about how this functions can be used with three python in-built functions which are filter(), map() and reduce(). In large projects, these concepts often make data manipulation easier. The filter() function takes two arguments-one is function itself and the other is the iterable which can be either list, tuple or other data structures. The syntax is filter(func, iterables). In the following example, we will use filter() method to output a list of numbers divisible by 5 from another list.

numbers = [23, 56, 90, 32, 50, 15, 87, 52]

divisible_by_five = list(filter(lambda x: x%5==0, numbers))

print(divisible_by_five)

The output when executing is:

image.png

The syntax of map() function is also same as filter() and both of them works same way syntatically. The only difference is that in map() the function passed as an argument is applied to all the items in the list whereas in filter() the function passed as an argument is applied to only items that returns true value. In our case above, the filter() function was applied to 90, 50 and 15 because they were the value that satisfies our condition. Now we will use map() function to this list of new value to divide them by 5.

numbers = [23, 56, 90, 32, 50, 15, 87, 52]

divisible_by_five = list(filter(lambda x: x%5==0, numbers))

print(divisible_by_five)

quotient = list(map(lambda y:y/5, divisible_by_five))

print(quotient)

We can see our desired output while running as below:

image.png

Now lets see about reduce() function. It has same syntax as filter() and map() but this function returns only single value as the meaning implied by the name i.e. reduction. Lets use this function to return a sum of items in the above list that contains the quotient after dividing by 5 in the above example.

from functools import reduce

numbers = [23, 56, 90, 32, 50, 15, 87, 52]

divisible_by_five = list(filter(lambda x: x%5==0, numbers))

print(divisible_by_five)

quotient = list(map(lambda y:y/5, divisible_by_five))

print(quotient)

sum = reduce(lambda a, b:a+b, quotient)

print(sum)

It seems like you need to import reduce from functools. You don't need to import in old version of Python. I am using 3.8 and seems like it has been moved to this module. The output of this code is:

image.png



0
0
0.000
0 comments