Using Python Map, Filter, and Reduce Methods

Thiago Abreu
2 min readAug 29, 2021

These are the methods that are widely used in analytic processes in Apache Hadoop and it is an important concept on functional programming using python.

Using Python Map Method

Before talking about Map function let's define a simple function and after we will talk about the Map method.

array_example = range(0,35)def cube_calc(foo):
return foo ** 3
for i in array_example:
print (cube_calc(i))

For each element on array_example, we calling cube_calc to calculate cube.

How to do this with just one line of code???
It's simple, we can use the Map function to perform this task.

map_function_list = map(cube_calc, array_example)
print(list(map_function_list))

The code above makes a map between the function created earlier and the elements of the array, getting the same result.

Using Python Filter Method

The filter method is designed to filter elements on a list.
The filter method returns the only elements where expression is evaluated to be true.

lst = range(1,22)def checkEvenNumber(num):
return num % 2 == 0
print(list(filter(checkEvenNumber, lst)))# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Let's see another example. Now we are filtering the only phrases that have "Python" in your content.

lst_phrases = [   'Go is a compiled language',
'Node.js is a JavaScript runtime',
'Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language',
'Python is an interpreted high-level general-purpose programming language',
'Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS.',
'Python is more popular on data science projects',
]def filter_python(lst):
return lst.count('Python') > 0
print(list(filter(filter_python, lst_phrases)))# ['Python is an interpreted high-level general-purpose programming language', 'Python is more popular on data science projects']

As we can see above, the filter method returns two items: [‘Python is an interpreted high-level general-purpose programming language’, ‘Python is more popular on data science projects’]

Using Python Reduce Method

The Reduce function does not be a part of the python standard and we need to import from functools. As the name suggests, this function reduces a list to a single value.

from functools import reducesum = reduce((lambda x, y : x + y), [1, 3, 5, 9])print(sum)
# 18

For more drops, follow me on Linkedin.

--

--