Press "Enter" to skip to content

Python Notes 10 : Map & Reduce built in functions

Map function takes in two arguments. map function applies the function to all the elements of sequence. It returns a new list (Python 2) with the elements changed by function. Map function returns iterators in Python 3.

Syntax

Map(function,sequence)

Example

def fahrenheit(T):
    return ((float(9)/5)*T + 32)

temp = [0, 22.5, 40,100]
F_temps = map(fahrenheit, temp)

#Show
F_temps
O/P ->
[32.0, 72.5, 104.0, 212.0]

Map with Lambda function

map(lambda x: (5.0/9)*(x - 32), F_temps)
OR
a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]

map(lambda x,y:x+y,a,b)
O/P->
[6, 8, 10, 12]
OR
# Now all three lists
map(lambda x,y,z:x+y+z, a,b,c)

 Reduce

The function reduce continually applies the function to the sequence. It returns a single value.

Syntax

reduce(function,sequence)

Example – 

lst =[47,11,42,13]
reduce(lambda x,y: x+y,lst)

Output
113

Explanation


If seq = [ s1, s2, s3, … , sn ], calling reduce(function, sequence) works like this:

  • At first the first two elements of seq will be applied to function, i.e. func(s1,s2)
  • The list on which reduce() works looks now like this: [ function(s1, s2), s3, … , sn ]
  • In the next step the function will be applied on the previous result and the third element of the list, i.e. function(function(s1, s2),s3)
  • The list looks like this now: [ function(function(s1, s2),s3), … , sn ]
  • It continues like this until just one element is left and return this element as the result of reduce()

Example 2

#Find the maximum of a sequence (This already exists as max())
max_find = lambda a,b: a if (a > b) else b
#Find max
reduce(max_find,lst)

Output
47
 

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *