@Note
Hil lam currently looking for some freelance projects. If you have a project idea in mind please
feel free to send me an email or check out my personal website. If you want to get to know
about my journey, you can read this article: How | got into programming
Docs »4, Map, Filter and Reduce
4. Map, Filter and Reduce
‘These are three functions which facilitate a functional approach to programming. We will discuss
them one by one and understand their use cases.
41. Map
‘isp applies a function to all the items in an input list. Here is the blueprint:
Blueprint
rnap(Function_to_apply, 1ist_of inputs)
Most of the times we want to pass all the list elements to a function one-by-one and then collect
the output. For instance:
tess = (2, 2, 3, 4) 5]
‘squared = {]
for iin Lens
squared. append(1**2)
ap allows us to implement this in a much simpler and nicer way. Here you go:
feess = [1 2, 3, 4, 5]
seuared = List(mip(lambda x
2, stens))
Most of the times we use lambdas with 2 so I did the same. Instead of a list of inputs we can
even have a list of functions!ef multiply 0
rretuen (0)
ef aza(x)
return (xx)
anes = (multiply, ad]
for 1 in range(s):
value= ist(map(lanbda x: (4), funes))
print(value)
# ovtpur:
# (6, 8)
#0, 2
#14, a
#13, 6)
#116, 8)
4.2. Filter
As the name suggests, #ilter creates a list of elements for which a function returns true. Here is a
short and concise example:
ronber_2ist - range(-s, 5)
ese than-tero'= List(fileer(Lanbds x: x < @, nunber_tst))
print(less-than_zero)
H outputs [-5,
“3-2, 4)
The filter resembles a for loop but itis a builtin function and faster.
Note: If map & filter do not appear beautiful to you then you can read about
comprehensions.
4.3. Reduce
feduce 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:
product = 2
Mist = (1, 2, 3, 4]
for non in list!
product = product * nun
# product = 24
Now let's try it with reduce:
from functools Amport reduce
product’ = reduce( (lambda x, y: x * ys [1s 2 3. 41)
# output: 24
-ntps0ok pythontips.comieniatestimap_lterhiml