top of page

Map, Filter, Reduce in Python

Before we jump straight into Map, Filter, and Reduce, we need to understand 2 simple concepts - 1) Higher-Order functions and 2) Lambda functions.


Higher Order Functions

A higher-order function is a function that takes in another function as an argument.

def myfunc(some_func, arg1):
    pass

def some_func(arg):
    pass

The functions map, filter & reduce we are discussing here are highter-order functions - their first parameter is function, and second parameter is iterable (list, tuple, dict, etc.,).

map(some_func, [1,2,3])
filter(some_func, [1,2,3,4])
reduce(some_func, [1,2,3,4])

Lambda Functions

Lambda functions are also called as anonymous functions, they don't have any name. The syntax:

lambda inputs: output

Let's take some lambda functions and their equivalent normal functions!

def func(x: int):
    return x*x

my_func = lambda x: x*x

print(my_func(5)) # output 25

Map

map is used to apply a transformation to every element in an iterable. For example, transforming [1, 2, 3] to [2, 4, 6] by multiplying every element in [1, 2, 3] by 2. The result of calling a map function, is a map object, instead of list. We need to convert the map object to list using list constructor.


Another example:


Filter

filter is used on an iterable to keep only certain elements that meet a certain condition. For examples only even numbers from a collection. For example, my input is [1,2,3,4,5,6,7,8,9,10] and my output collection is [2,4,6,8,10]. Like map function, filter function also returns a filter object, and it needed to be converted to a list.


Another example, from the given input collection, it filters all palindrome strings.

Reduce

reduce is used on an iterable to combine all its elements in some way. For example, we want to multiply all numbers in [1,2,3,4] together to get 24. Here, our lambda function needs to take two input arguments, and multiply them together.


Here we need to import reduce from functools module.

Another example, to join all strings in the list, as one string with '-' seperated.

list1 = ["one", "two", "three", "four"]
print(reduce(lambda x,y: x+"-"+y, list1))

## output
one-two-three-four

 
Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark


253 views0 comments

Recent Posts

See All

Kommentare

Mit 0 von 5 Sternen bewertet.
Noch keine Ratings

Rating hinzufügen
bottom of page