How to use Lambda, filter, reduce, and map in Python Programming

f = lambda x, y: x+y
f(1,1)

The map() function

r = map(func, map)
def fahrenheit(T):
return ((9/5)*T + 32)
def celsius(T):
return (5/9) * (T-32)
temp = [36.5, 32, 38, 40]F = map(fahrenheit, temp)
C = map(celsius, F)
print (list(F))
print (list(C))
Celsius = [36.5, 32, 38, 40]
Fahrenheit = map(lambda x: (9/5)*x + 32, Celsius)
C = map(labmda x: (5/9)*(x-32), Fahrenheit)

Filtering

>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print list(result)
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]

Reducing a List

  • At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, s2), s3, … , sn ]
  • In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1, s2),s3)
    The list looks like this now: [ func(func(s1, s2),s3), … , sn ]
  • Continue like this until just one element is left and return this element as the result of reduce()
>>> from functools import reduce
>>> reduce(lambda x,y: x+y, [47,11,42,13])
113
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>> reduce(lambda x, y: x+y, range(1, 51))
1275

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store