Python map filter and reduce

Map, Filter and Reduce

Map

Map applies a function to all the items in an input_list. Given an example:

1
2
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

The use blueprint is

1
map(function_to_apply, list_of_inputs)

Note that the function could be list of functions.

Filter

As the name suggests, filter returns the list of elements for which a function returns true. Given an example:

1
2
3
4
5
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]

Reduce

Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. For example, if you wanted to compute the product of a list of integers.

So the normal way you might go about doing this task in python is using a basic for loop:

1
2
3
4
5
6
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num

# product = 24

Now let’s try it with reduce:

1
2
3
4
5
6
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])

# Output: 24
# map and filter are both in built-in module.
# The REDUCE need to be imported.

Reference

  1. Map, Filter and Reduce https://book.pythontips.com/en/latest/map_filter.html