Working with Python – Map, Filter and Reduce Function
Introduction
In this blog post, we are trying to discuss about Map, Filter and Reduce function of Python. These functions are very important and please try to understand that. We are using Lambda function with that. It is important in this seance that the Map-reducing architecture of Hadoop is built on that.
Hope it will be interesting.
Map
Function
The syntax is:
Map(function, iteration)
In the above picture a pictorial diagram is added. We have a Lit. What MAP function does, it take each element from the list and pass it to the FUNCTION. The function returns a value and replaces the item of the list with that value.
In our syntax, the Function
may be a normal function or a Lambda Function and the Iteration is the List object.
Example
with Lambda Function:
lst=[1,2,3,4,5]
x=list(map(lambda a: a*5, lst))
print(x)
[5, 10, 15, 20, 25]
Let’s analyze it.
x=list(map(lambda a: a*5, lst))
Example
with Function:
def myfunc(a):
return(a*5)
lst=[1,2,3,4,5]
x=list(map(myfunc, lst))
print(x)
[5, 10, 15, 20, 25]
Filter
Function
As the name define it just filter elements from the Iteration
The syntax is:
Filter(function, iteration)
Example
with Lambda Function:
lst=[1,2,3,4,5]
x=list(filter(lambda a: a>2, lst))
print(x)
[3, 4, 5]
Example
with Function:
def myfunc(a):
if a>2:
return(a)
lst=[1,2,3,4,5]
x=list(filter(myfunc, lst))
print(x)
[3, 4, 5]
Reduce Function
It just returns a Single value.
The syntax is:
Reduce(function, iteration)
Example
with Lambda Function:
from functools import reduce
lst=[1,2,3]
x=list(reduce(lambda a:a*a, lst))
print(x)
à6
Example
with Function:
def myfunc(a):
return(a*a)
from functools import reduce
lst=[1,2,3]
x=list(reduce(myfunc, lst))
print(x)
à6
Hope you like it.
Comments
Post a Comment