Python most powerful functions: map(), filter(), and reduce() in 5 minutes

Hardikkumar Dhaduk 29 May, 2023 • 5 min read

This article was published as a part of the Data Science Blogathon

Overview

Python includes a number of predefined built-in functions that can be utilized by the end-user by simply calling them. These functions not only make programmers’ jobs easier, but they help establish a common coding environment. In this tutorial, you’ll learn about three of Python’s most powerful functions: map(), filter(), and reduce().

Functional programming’s three pillars are map, filter, and reduce functions. While Python isn’t exactly a functional programming language, it does have a lot of features that make it so. The map, filter, and reduce functions in Python are discussed in this article, as well as how they correspond to functional programming principles.

Functional Programming

A programming paradigm that uses functions to define computation is known as functional programming. The concept of an unchangeable state is one of functional programming’s key defining traits.

Computation is done through statements in imperative programming, which is arguably the most prevalent programming paradigm you’re already familiar with. These are commands that affect the value of a variable, and thus the state of the computation after they are executed. A for loop, for example, can execute a statement repeatedly, altering the value of a variable each time, as shown below:

counter = 0
for i in range(10):
    counter += 1

Each time the value of the counter is increased by one in each iteration of the loop, the state of the calculation changes, bringing it closer to the end state.

Before we go into examples of ‘map()’, ‘filter()’, and ‘reduce()’ functions in Python, we’ll need to go over another concept: higher-order functions.

Higher-Order Functions

In functional programming, higher-order functions are our primary tool for defining computation. These are functions that take a function as a parameter and return a function as the result. Reduce(), map(), and filter() are three of Python’s most useful higher-order functions. They can be used to do complex operations when paired with simpler functions.

A higher-order function is demonstrated in the code sample below. print greeting() takes two arguments: a function f and a name n, and returns the result of calling f. (n).

def greet(name):
    return "Hello, {}!".format(name)

def print_greeting(f, n):
    print(f(n))

Anonymous Functions

We saw an example of a function that takes another function as an argument in the previous section. The functions map(), filter(), and reduce() all do the same thing: They each take a function and a list of elements, and then return the result of applying the function to each element in the list.

As previously stated, Python has built-in functions like map(), filter(), and reduce(). Python’s functional programming feature is enabled through these functions. The only factors that determine the output in functional programming are the inputs passed in. These functions can accept any other function as a parameter and can also be passed as parameters to other functions. Let’s look at each of these functions in more detail now.

we have three main functions:

  1. map()
  2. filter()
  3. reduce()

The map() function:

The map() function or map and filter in Python (also called as map filter in Python) is a higher-order function. As previously stated, this function accepts another function and a sequence of ‘iterables’ as parameters and provides output after applying the function to each iterable in the sequence. It has the following syntax:

SYNTAX: map(function, iterables)

The function is used to define an expression which is then applied to the ‘iterables’. User-defined functions and lambda functions can both be sent to the map function.

User-defined functions can be sent to the map() method. The user or programmer is the only one who can change the parameters of these functions.

EXAMPLE

x is a map object, as you can see. The map function is displayed next, which takes “function()” as a parameter and then applies “a * a” to all ‘iterables’. As a result, all iterables’ values are multiplied by themselves before being returned.

Let’s look at how lambda functions can be used within the map() method to reduce map filter python.

Lambda within map() functions:

Functions with no name are known as lambda functions. These functions are frequently used as input to other functions. Let’s try to integrate Lambda functions into the map() function.

EXAMPLE

tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)
newtuple = tuple(map(lambda x: x+3 , tup)) 
print(newtuple)

OUTPUT

(8, 10, 25, 100, 57, 65, 80, 26, 76, 64)

The filter() function:

The filter() function is used to generate an output list of values that return true when the function is called. It has the following syntax:

SYNTAX: filter (function, iterables)

This function like map(), can take user-defined functions and lambda functions as parameters.

EXAMPLE

def func(x):
    if x>=3:
        return x
y = filter(func, (1,2,3,4))  
print(y)
print(list(y))

OUTPUT

[3, 4]

As you can see, y is the filter object, and the list is a collection of true values for the condition (x>=3).

Lambda within filter() functions:

The condition to be checked is defined by the lambda function that is provided as an argument.

EXAMPLE

y = filter(lambda x: (x>=3), (1,2,3,4))
print(list(y))

OUTPUT

[3, 4]

The reduce() function:

The reduce() function applies a provided function to ‘iterables’ and returns a single value, as the name implies.

reduce function | python most powerful functions

SYNTAX: reduce(function, iterables)

The function specifies which expression should be applied to the ‘iterables’ in this case. The function tools module must be used to import this function.

EXAMPLE

from functools import reduce
reduce(lambda a,b: a+b,[23,21,45,98])
 

OUTPUT

187

The reduce function in the preceding example adds each iterable in the list one by one and returns a single result.

The Python functions map(), filter(), and reduce() can all be used together.

So, This article on map(), filter(), and reduce functions in Python. I hope you have understood everything clearly. Make sure you practice on map(), filter(), and reduce() because this function is very useful when we are doing data analysis using python.

Frequently Asked Questions

Q1. What is map () and reduce () functions in Python?

A. In Python, the map() and reduce() functions are built-in higher-order functions used for iterable manipulation.
The map() function applies a given function to each item in an iterable, creating a new iterable with the results. For example, map(square, [1, 2, 3]) would return an iterable with the squared values: [1, 4, 9].
On the other hand, the reduce() function applies a specified function to the first two elements of an iterable, then to the result and the next element, and so on, reducing the iterable to a single value. For instance, reduce(add, [1, 2, 3]) would yield 6 (1 + 2 + 3).
Note: Both map() and reduce() functions require importing the functools module.

Q2. What is the difference between filter map and reduce in Python?

A. In Python, filter(), map(), and reduce() are three built-in functions used for iterable manipulation.
filter() creates a new iterable by applying a filtering function to each element of the input iterable, returning only the elements that satisfy a given condition.
map() applies a transformation function to each element of the input iterable, creating a new iterable with the transformed values.
reduce() combines elements of the input iterable using a specified function, progressively reducing it to a single value by applying the function to pairs of elements.
In summary, filter() filters elements, map() transforms elements, and reduce() aggregates elements to a single value.

EndNote

Thank you for reading!
I hope you enjoyed the article and increased your knowledge.
Please feel free to contact me on Email
Something not mentioned or want to share your thoughts? Feel free to comment below And I’ll get back to you.

About the Author

Hardikkumar M. Dhaduk
Data Analyst | Digital Data Analysis Specialist | Data Science Learner
Connect with me on Linkedin
Connect with me on Github

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.
Hardikkumar Dhaduk 29 May 2023

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Joy Mukerjee
Joy Mukerjee 20 May, 2022

Error- Map returned true and false and filter returned values. In the above you have stated that vice-versa a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11] filtered = filter (lambda x: x % 2 == 0, a) print(list(filtered)) [100, 2, 8, 60, 4, 10] mapped = map(lambda x: x%2 == 0, a) print(list(mapped)) [True, True, True, True, False, True, False, False, True, False]

Bavi
Bavi 17 Jun, 2022

Easy to understand sir😃 Thank you

Trevor
Trevor 24 Jul, 2022

Map() and filter() are nice, but there are better equivilents with generator expressions - Guido even wanted to remove map/filter/reduce at some point. Generators are definitely easier to read, and also save a lambda call overhead (adds up if iterating millions of items). Using the same examples - ``` tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61) // Map version, from article newtuple = tuple(map(lambda x: x+3 , tup)) // Equivilent generator version newtuple = tuple(x + 3 for x in tup) ``` ``` # Filter version, from article y = filter(lambda x: (x>=3), (1, 2, 3, 4)) # Equivilent generator version y = (x for x in (1, 2, 3, 4) if x >= 3) ``` Still a good article from the functional programming standpoint, just good to know that there are cleaner alternatives

Python
Become a full stack data scientist