Monday, January 23, 2017

Lambda, Map, Filter, and Reduce function in python

Lambda , map, filter, and reduce. - These functions are borrowed from functional programming.

Lambda function¶

• a simple one line function
• no def or return keywords
Example¶
Let's write a python funtion to find maximum of two numbers.
1) Normal way:¶
In [28]:
def max_between(x,y):
if x>y:
return x
else:
return y
print(max_between(10,80))

80

2) Lambda funtion to find maximum of two numbers¶
In [29]:
max_bet_lambda = lambda x,y:x if x>y else y

In [30]:
print(max_bet_lambda(10,80))

80


Map function¶

• Map function are used to apply a same funtion to each element in a sequence.
• Returns a modified sequence
Syntax: map(function,list) : returns an object. Convert it to a list.
In [31]:
def mul_2(x):
return 2*x
num_list = [1,2,3,4,5]
a = map(mul_2,num_list)
print(a)
print(list(a))

<map object at 0x10623a2b0>
[2, 4, 6, 8, 10]

In [32]:
num_list = [1,2,3,4,5]
print(list(map(lambda x: 2*x,num_list)))

[2, 4, 6, 8, 10]

Note : In list comprehension way:¶
In [33]:
print([2 * x for x in num_list])

[2, 4, 6, 8, 10]


Filter funtion¶

• This function filters element in a sequence based on a given condition.
• It returns a filtered list.
Finding even numbers in a list using filter function.¶
In [34]:
num_list = [1,2,3,4,5,6,7,8,9,10]
print(list(filter(lambda x: x%2==0,num_list)))

[2, 4, 6, 8, 10]

Note : In a list comprehension way:¶
In [35]:
print(list(x for x in num_list if x %2==0))

[2, 4, 6, 8, 10]


Reduce function¶

• This function apply a same operation to all the elements in a sequence.
• It uses result of first operation as a first param to the next operation.
• It returns a single value, and not a list
• To use reduce function, import reduce from functools package.
Multiply all the values in a list¶
In [38]:
from functools import reduce
num_list = [1,2,3,4,5]
print(reduce(lambda x,y : x*y,num_list))

120