Map, Filter, Reduce
Code sample link: https://replit.com/@jjoco/python-functional
These functions help the developer take a more functional approach to some problems.
Let's say we have an items
list:
1 |
|
map
The map
function allows the developer to apply a function to all items in a list, and returns an iterator that contains the output values.
Syntax
1 |
|
Check out the following:
1 2 |
|
list
is needed to cast the iterator into a list. In this example, we create multiply each value in items
by 2, and put the output results in a new list. FYI, you could also do the above using list comprehensions.
filter
filter
creates a new list that contains the values of some base list based on some condition function.
Syntax
1 |
|
For example,
1 2 |
|
items
that is not negative.
reduce
reduce
is used to do some computation on an entire list, instead of each element separately. It performs a rolling computation on sequential pairs in the list in order to accumulate the elements into a single value.
Firstly, we need to import reduce
from the functools
library and use the following syntax:
1 2 |
|
Consider the following:
1 2 3 4 |
|
reduce
to get the sum of the given items
list.