Map, Filter and Reduce
Map
Map
applies a function to all the items in an input_list. Given an example:
1 | items = [1, 2, 3, 4, 5] |
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 | number_list = range(-5, 5) |
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 | product = 1 |
Now let’s try it with reduce:
1 | from functools import reduce |
Reference
- Map, Filter and Reduce https://book.pythontips.com/en/latest/map_filter.html