Map() function
The advantage of the lambda operator can be seen when it is used in combination with the map() function.
map() is a function with two arguments:
The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func.
The below example of the map() function doesn’t use lambda. By using lambda, we wouldn't have had to define and name the functions fahrenheit() and celsius().
def fahrenheit(T):
return((float(9)/5) * T + 32)
def celsius(T):
return(float(5)/9) * (T - 32)
temp = (36.5, 37, 37.5, 39)
F = map(fahrenheit, temp)
C = map(celsius, F)
The below example of the map() function use lambda:
temp2 = [39.2, 36.5, 37.3, 37.8]
Farhenheit = map(lambda x: (float(9)/5) * x + 32, temp2)
print(Farhenheit)
Celsius = map(lambda x: (float(5)/9) * (x - 32), Farhenheit)
print(Celsius)
map() can be applied to more than one list but the lists have to have the same length.
map() will apply its lambda function to the elements of the argument lists, i.e. it first applies to the elements with the 0th index, then to the elements with the 1st index until the n-th index is reached.
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9]
map(lambda x,y: x+y, a,b)
map(lambda x,y,z: x+y+z, a,b,c)
map(lambda x,y,z: x+y-z, a,b,c)