Map/Filter/Reduce in Python to avoid loops

These three are the higher order Functions in Python. Why are they called higher-order? Because Map, Filter, and Reduce accept other functions as arguments. With the help of them, one can avoid the usage of lengthy codes or loops.

images

MAP

The map() function in Python applies a given function to each item of an iterable (like a list, tuple, etc.) and returns a new iterable with the results.

The code snippet is:

Here, I made a list of names of fruits, and a function that calculates the length of the argument passed while calling. With the use of the map() function, you can easily find the length of each string in the list.

lst=['Apple','Mango','Grapes']
def myfunc(a):
    return len(a)
x= list(map(myfunc,lst))
print(x)

FILTER

The filter() function filters elements of an iterable based on a function that returns True or False. It returns an iterator containing the elements for which the function returns True.

The code snippet is:

Here, I made a list of numbers and a function that returns those numbers that are greater than 50. With the use of the filter() function, you can easily filter out the desired output.

l1=[23,34,45,56,67,78]
def func1(a):
    return a>50
x1= list(filter(func1,l1))
print(x1)

REDUCE

The reduce() function is in the functools module. It applies a rolling computation to sequential pairs of values in a list, reducing them to a single value.

The code snippet is:

Firstly, import the reduce function from functools library. Secondly, made a list of numbers and a function that returns the cumulative sum of all numbers in the list. With the use of the Reduce() function, you can easily find out the desired output.

from functools import reduce
def func2(x,y):
    return x+y
l1=[23,34,45,56,67,78]
x3=reduce(func2,l1)
print(x3)