Filter Map Reduce in python | python tutorials
Filter Map Reduce in python | python tutorials
1. Filter
Python’s filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition.
This process is commonly known as a filtering operation. With filter(), you can apply a filtering function to an iterable and produce a new iterable with the items that satisfy the condition at hand.
def is_even(a):Output
return a%2==0
lst = [2,3,4,6,7,3,1,23,76]
n = list(filter(is_even,lst))
print(n)
[2, 4, 6, 76]Using Lamda function
lst = [2,3,4,6,7,3,1,23,76]
evens = list(filter(lambda n: n%2==0, lst))
print(evens)
[2, 4, 6, 76]
Python’s map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping.
map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
def update(n):
return n+2
lst = [2,3,4,6,7,3,1,23,76]
# evens = list(filter(lambda n: n%2==0, lst))
doubles = list(map(update,evens))
print(evens)
print(doubles)
[4, 6, 8, 78]using lamda function
# def update(n):
# return n+2
lst = [2,3,4,6,7,3,1,23,76]
evens = list(filter(lambda n: n%2==0, lst))
doubles = list(map(lambda n: n +2 ,evens))
print(evens)
print(doubles)
3. Reduce
Python’s reduce() is a function that implements a mathematical technique called folding or reduction.
reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.
from functools import reduce
# def add_all(a, b):
# return a+b
lst = [2,3,4,6,7,3,1,23,76]
evens = list(filter(lambda n: n%2==0, lst))
doubles = list(map(lambda n: n +2 ,evens))
sum = reduce(lambda a,b: a+b, evens)
# sum = reduce(add_all,doubles)
print(evens)
print(doubles)
print(sum)
[2, 4, 6, 76] [4, 6, 8, 78] 88
Post a Comment