Using Python Lambda, Reduce, Map and Filter
Python Lambda, Reduce, Map and Filter

Lambda, map, filter, reduce

Typically I use list, dictionary and set comprehensions over using lambda and map. But you may prefer this.

Lambda

The syntax is lambda variables: function.

In [1]:
add = lambda x, y: x + y
add(2, 3)
Out[1]:
5
In [3]:
multiply = lambda x, y: x * y 
multiply(2, 3)
Out[3]:
6

Map

The syntax is map(function, sequence).

In [3]:
lst = [i for i in range(11)]
In [4]:
lst
Out[4]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This works in Python 2.

In [4]:
square_element = map(lambda x: x**2, lst)
print(square_element)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

For Python 3, you have to explicitly return a list.

In [5]:
square_element = list(map(lambda x: x**2, lst))
print(square_element)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

If you would like to apply map to multiple lists, map would apply the function to the first index.

In [1]:
lst_1 = [1, 2, 3, 4]
lst_2 = [2, 4, 6, 8]
lst_3 = [3, 6, 9, 12]
In [3]:
add_elements = map(lambda x, y: x + y, lst_1, lst_2)
add_elements
Out[3]:
[3, 6, 9, 12]
In [8]:
add_elements = map(lambda x, y ,z : x + y + z, lst_1, lst_2, lst_3)
add_elements
Out[8]:
[6, 12, 18, 24]

Filter

The syntax is filter(function, list).

In [13]:
lst = range(11)
lst
Out[13]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [15]:
multiples_of_three = filter(lambda x: x % 3 == 0, lst)
multiples_of_three
Out[15]:
[0, 3, 6, 9]

Reduce

The syntax is reduce(function, sequence). The function is applied to the elements in the list in a sequential manner. Meaning if lst = [1, 2, 3, 4] and you have a sum function, you would arrive with ((1+2) + 3) + 4.

In [16]:
lst = range(11)
lst
Out[16]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [18]:
sum_all = reduce(lambda x, y: x + y, lst)
sum_all
Out[18]:
55
Tags: python