Map, Reduce and Filter Operations in Python
In this tutorial, we will learn about 3 inbuilt functions in Python. These functions are very versatile. They frequently used in Python language to keep the code more readable and better. So let’s learn Map, Reduce and Filter Operations in Python with examples.
Map Function in Python
The map function is for the transformation of values in a given sequence. This is done with the help of functions. It takes exactly two input arguments namely:
1. iterable object to proceed
2. the function object
Syntax: result = map(function , iterable object)
The function argument may be defined via:
- the conventional method
- the help of lambda expression.
Syntax: lambda arguments : expression
Illustration for “lambda” function
# program to use lambda function # we are making a function to calculate the square of a number square= lambda x: x**2 print(square(7))
Source Code: Map Function
# how to implement map function # here we are defining the function with the help of lambda expression as discussed in the above example lst=["7","9","5","2","0"] # defining function within arguments print(map(lambda( y: y ** 2, lst)) # using function object as argument print(map(square, lst))
Output: [49,81,25,4,0] [49,81,25,4,0]
In this example, we are able to implement how to use map function which allows us to make a list with the help of function object and list of input values.
Reduce Function in Python
This function is available in the inbuilt module functools. It takes exactly two arguments
1. an iterable object
2. a function object
Source Code: Reduce Function
Suppose we wish to compute the sum of squares of numbers in a list. This involves the repetitive addition of two terms together in a file by using the iterative approach. By the help of reduce function, we can reduce the time of computation by performing additions in a parallel environment.
# how to implement reduce function in Python 3.x. or earlier import functools as ft cubes=list(map(lambda( x: x ** 3,lst )) sum_cubes=ft.reduce(lambda x,y : x + y,cubes) print(sum_cubes)
Filter Function in Python
This function allows us to filter out elements in a list satisfying the given set of constraints or conditions. Suppose we wish to calculate the sum of cubes which are even then we can take the help of filter function. The function takes totally two arguments :
1. a function object
2. an iterable object
Source Code: Filter Function
# demonstration of filter function in Python 3.x. or earlier evencubes=list(filter(lambda x: x%2==0,cubes)) print(evencubes)
We hope you have got a clear concept of Map, Reduce and Filter Operations in Python.