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 :
add = lambda x, y: x + y

Out:
5
In :
multiply = lambda x, y: x * y
multiply(2, 3)

Out:
6

### Map¶

The syntax is map(function, sequence).

In :
lst = [i for i in range(11)]

In :
lst

Out:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This works in Python 2.

In :
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 :
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 :
lst_1 = [1, 2, 3, 4]
lst_2 = [2, 4, 6, 8]
lst_3 = [3, 6, 9, 12]

In :
add_elements = map(lambda x, y: x + y, lst_1, lst_2)

Out:
[3, 6, 9, 12]
In :
add_elements = map(lambda x, y ,z : x + y + z, lst_1, lst_2, lst_3)

Out:
[6, 12, 18, 24]

### Filter¶

The syntax is filter(function, list).

In :
lst = range(11)
lst

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

Out:
[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 :
lst = range(11)
lst

Out:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In :
sum_all = reduce(lambda x, y: x + y, lst)
sum_all

Out:
55
Tags: