Map, Filter and Reduce Functions in Python

Divy Shah
2 min readJan 31, 2021

Map

Map is a function that works like list comprehensions and for loops. It is used when you need to map or implement functions on various elements at the same time.

Syntax Of map function

map(function , iterable object)

The Function here is lambda function or any other function object.

Iterable object can be list, tuple, string, set, dictionary any

Example

a = ['India', 'America', 'China', 'Russia']print(list(map(lambda x: len(x), countries)))

Output: [5, 7, 5, 6]

in this code snippet lambda function returns the function object but the map function handle the iterable part by passing each different list values in function. then lambda function returns the length of each string as a output.

Filter

filter() is a is a similar to the map() but the difference is that it requires the function to look for a condition and returns only those elements from the collection that satisfy the condition.

Syntax of filter function

filter(function,iterable object)

The function object passed to the filter function should always return a boolean value.

Iterable object can be list, tuple, string, set, dictionary any

Example

Let’s try to filter even number from the list

l = [1, 2, 4, 6, 7, 8, 9]d = filter(lambda x: x%2==0, l)print(list(d))

Output: [2, 4, 6, 8]

in this code we used lambda funton which returns the True if number is even and here we passed the iterable object as a list. as a result we got list of even numbers from the passed list.

Reduce

Reduce is an operation that breaks down the entire process into pair-wise operations and uses the result from each operation, with the successive element.

Syntax of reduce function

reduce(function,iterable object)

The function object passed to the reduce function decides what expression is passed to the iterable object.

Iterable object can be a string, list, tuple, set or dictionary.

Also, reduce function produces a single output.

in python we can import the reduce function from functools.

Here the one thing is to note down is reduce funciton must have 2 parameter.

Example

from functools import reducel = [1, 2, 3, 4]
print(reduce(lambda x, y: x*y, l))

Output: 24

here you all noticed one thing that reduce function always return a single value result as a output.

--

--