11 posts
map, filter and reduce are the functions by which we can achieve functional programming in python.
map: This applied the function definition to each item in the input_list.
map(function_to_be_applied, input_list)
Example : Squares of the elements in the input_list
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i*i)
print(squared)
items = [1, 2, 3, 4, 5]
print(list(map(lambda x: x*x, items)))
Result: [1, 4, 9, 16, 25]
filter: As the name suggests it just filters the original input_list according to the function definition and gives the output.
filter(function_to_be_applied, input_list)
Example: Filter out the negative numbers in the list.
list = [1, -9, -3, 4, 5]
positiveNumbers = []
for i in list:
if i > 0:
positiveNumbers.append(i)
print(positiveNumbers)
list = [1, -9, -3, 4, 5]
print(list(filter(lambda x: x>0, list)))
Result: [1, 4, 5]
reduce: computatation will be performed on the sequential pairs of a list, and returns back single result unlike map and filter.
reduce(function_to_be_applied, input_list)
Example: Calculate the element's sum in the list
input_list = [1, 2, 3, 4, 5]
sum = 0
for i in input_list:
sum += i
print(sum)
import functools
input_list = [1, 2, 3, 4, 5]
sum = functools.reduce(lambda x,y: x+y, input_list)
print(sum)
Result: 15
There is an accumulate method which is there in itertools modules gives the similar results.
To check that out Difference Between reduce & accumulate
Please log in to leave a comment.