Python : lambda, map, filter, reduce functions

lambda functions
Find prime numbers(not the most efficient one, though)

nums = range(2, 50) 
for i in range(2, 8):
	nums = filter(lambda x: x == i or x % i, nums)

print nums

#Output : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

The above algorithm is called “the sieve of Eratosthenes

filter(), map() and reduce() – they expect two arguments: A function and a list.
filter() to filter the list based on condition.
map() is used to convert the list.
reduce() is bit different and the “worker function” for this one must accept two arguments.

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> 
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>> 
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>> 
>>> print reduce(lambda x, y: x + y, foo)
139

reduce() – The function is called with the first two elements from the list, then with the result of that call and the third element, and so on, until all of the list elements have been handled

2 thoughts on “Python : lambda, map, filter, reduce functions

Leave a comment