Python: lambda, map, filter, reduce

A short introduction to functional programming

Python: lambda, map, filter, reduce
Photo by David Clode on Unsplash
Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…

A function without name is called a lambda expression and has only one expression.

Example:square = lambda num: num * num
print(square(2))
4

Map

The map function accept another function and a list as parameters; the output is provided after applying the function to each of the list elements. Map can accept normal functions and lambda expressions.

Example:square = map(lambda num: num * num,[1,2,3,4,5])
print(list(square))
[1, 4, 9, 16, 25]

Filter

The filter function like the map function accepts another parameter as function and a list as parameters; filter returns the values of the list passed as parameter where the function which evaluates them returns True.

Example:evens = filter(lambda num: num % 2,[1,2,3,4,5])
print(list(evens))
[1, 3, 5]

Reduce

The reduce function accepts three mandatory parameters and a fourth parameter optional, it reduce always return a single value which is the result of the lambda expression which must return a single number.

Example:from functools import reduce
print(reduce(lambda a, sum: a + sum, [1,2,3,4,5]))
15

The fourth parameter is the starting value of the result variable, in this example the result is not 15 but 25 because sum initial value is 10print(reduce(lambda a, sum: a + sum, [1,2,3,4,5],10))
25

Combining map, filter and reduce

You can combine map, filter and reduce to a single one-liner.. its cool but a bit unreadable.

Example:list(filter(lambda num: num % 2, list(map(lambda num: num * num,[1,2,3,4,5]))))
[1, 9, 25]

I hope you found this article useful :)

Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…