Easy way to IT Job

Map, Filter, and Reduce Functions in Python
Share on your Social Media

Map, Filter, and Reduce Functions in Python

Published On: April 6, 2024

When it comes to Python programming, there are a few powerful functions that can greatly improve your capacity for effective data manipulation. The map, filter, and reduce functions are a few of them. Although these functions may appear straightforward at first, learning them can lead to a wealth of opportunities for clear, understandable, and effective code. We’ll examine each of these functions in detail in this article, covering their syntax, use cases, and goals. Learn comprehensively with hands-on exposure through our Python course syllabus.

What is Functional Programming?

Functional programming is a programming paradigm that defines computation using functions. One of the main characteristics that distinguishes functional programming is the idea of an immutable state.

Imperative programming, maybe the most common programming paradigm you are already familiar with, uses statements to do computation. These are commands that, when they are carried out, change a variable’s value and, consequently, the computation’s state. 

Example: 

A for loop can repeatedly run a statement, changing a variable’s value each time, as the example below illustrates:

counter = 0

for i in range(10):

    counter += 1

The calculation’s state shifts, getting closer to the final state with each iteration of the loop when the counter value is increased by one. Before delving into instances of Python’s “map(),” “filter(),” and “reduce()” functions, we must discuss an additional idea: higher-order functions. 

Higher-Order Functions

Higher-order functions are our main tool for defining computation in functional programming. These are the functions that, when given a function as an input, produce a function as the output. Three of Python’s most helpful higher-order functions are reduce(), map(), and filter(). When combined with other simpler functions, they can be utilized to perform complex processes.

The code example below illustrates a higher-order function. print hello() returns the outcome of calling function f. (n) and accepts two arguments: a function f and a name n. 

def greet(name):

    return “Hello, {}!”.format(name)

def print_greeting(f, n):

    print(f(n))

Anonymous Functions

In the part before this one, we saw an illustration of a function that accepts an argument from another function. The following is what the functions reduce(), filter(), and map() all accomplish: They all take in a list of elements and a function, and they all return the result of iterating through each element of the list using the function.

As mentioned earlier, built-in Python functions include reduce(), filter(), and map(). These routines allow for the use of Python’s functional programming capabilities. The results of functional programming depend entirely on the inputs given. Both these functions and other functions can take these as parameters and pass them to one another. Now let’s examine each of these roles in greater depth. Have you ever wondered why you should learn Python? Find your answer here.

Understanding Map, Filter, and Reduce

Let’s quickly review each function’s general goals before getting into more detail about each one in turn:

Map Function: The map function creates a new iterable with the results of applying a specified function to each element of an iterable (like a list). In essence, it modifies every component of the input sequence under a given function. 

Filter Function: The filter function creates a new iterable that only includes the items for which the predicate returns ‘True’ by applying a provided predicate—a function that can return ‘True or False’ to each item in an iterable. Stated differently, it excludes some items according to specified criteria.

Reduce Function: Unlike map and filter, the reduction function is now part of the functools module in Python 3, rather than being a built-in function. It repeatedly reduces the elements of an iterable to a single value by applying a binary function to them.

Map Function in Python

The map() function, commonly known as map and filter or map filter in Python, is a higher-order function. As mentioned earlier, this function produces output after applying the function to each iterable in the sequence. It takes as input another function and a series of “iterables.”

Syntax

map(function, iterable)

Here, the function is the function to be applied to each element of the iterable, and iterable is the sequence of elements to be mapped. The map function returns an iterator, so you often need to wrap it with a list() to see the results immediately.

Example

def square(x):

    return x * x

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(square, numbers))

print(squared_numbers) 

Output

[1, 4, 9, 16, 25]

In this example, a new list containing the squares of all the numbers is created by applying the square function using a map to each element of the number list.

Lambda within the map() functions

Lambda functions are those that have no name. It is common practice to utilize these functions as input for other functions. Incorporate Lambda functions into the map() method, let’s try.

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)

Python-related article on Softlogic: Goto Statement in Python.

Filter Function

When the filter() method is used, an output list of values that return true is produced. Its syntax is as follows:

Syntax

filter (function, iterables)

Example

def func(x):

    if x>=3:

        return x

y = filter(func, (1,2,3,4))  

print(y)

print(list(y))

Output

[3, 4]

Lambda within the filter() functions

The lambda function that is passed in as an input defines the condition to be tested.

Example

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

print(list(y))

Output

[3, 4]

Reduce Function

As previously indicated, Python 3’s functools package now includes the reduction method. It functions differently from a map and filter because it applies a cumulative binary function to the items, reducing the iterable to a single value. 

Syntax

reduce(function, iterable)

Example

def add(x, y):

    return x + y

numbers = [1, 2, 3, 4, 5]

sum_of_numbers = reduce(add, numbers)

print(sum_of_numbers)

Output

5 (1 + 2 + 3 + 4 + 5)

Practical Applications

Now that we know how the map, filter, and reduce functions operate, let’s look at some real-world scenarios where they can come in quite handy:

Data Transformation: You frequently need to transform data in different ways while working with datasets. A map is an effective way to apply a transformation function to every piece of data.

Data Filtering: One of the most frequent tasks in data processing is to remove undesirable parts from a dataset by applying specific criteria. Filter simplifies and shortens this task.

Aggregation: You may need to aggregate the data to obtain the maximum, average, or sum of the values when working with huge datasets. For these kinds of aggregating operations, reduction is ideal. 

Conclusion

To sum up, Python’s map, filter, and reduce functions are effective tools for handling data clearly and straightforwardly. You may develop simpler, more expressive code that is easier to read and update by becoming proficient with these functions. These functions are great additions to your Python toolset, whether you’re working with large data analytics or small-scale data processing. Try them out in your projects to observe how they can simplify your code and improve your experience as a programmer. Discover a wide range of careers in the software development field by enrolling in our Python training in Chennai at Softlogic Systems.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.