DEV Community

loading...

Map, reduce and all these stuff

mandrewcito profile image Andrés Baamonde Lozano Updated on ・1 min read

Continuing with a functional approach of python we take a look to the List functions. we will provide a little example for each one of this functions. This functions are map, reduce and filter.

Map

Map applies a function to each one of the elements of a sequence

secuence = list(range(0,10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
f = lambda x: x + 1
map(f, secuence)
# result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

Filter

Filter reduces a secuence depending of a boolean function

secuence = list(range(0, 10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
f = lambda x: x % 2 == 0
filter(f, secuence)
#result = [0, 2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Reduce

Reduce, is a operation that "reduces a list" apliying an operator

from functools import reduce
secuence = list(range(0, 10))
# secuence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
f = lambda x, y: x + y
reduce(f,secuence)
# result = 45
# Using initial value, thanks to @magicleon94
reduce(f,secuence, 10)
# result = 55

Enter fullscreen mode Exit fullscreen mode

Discussion (4)

pic
Editor guide
Collapse
magicleon94 profile image
Antonello Galipò

An interesting thing you might point out is that reduce takes an optional third parameter, which is an initial value. This could be useful in some situation

Collapse
mandrewcito profile image
Andrés Baamonde Lozano Author

I will add it to post, thanks!

Collapse
thebadcoder profile image
TheBadCoder

Could you please explain statement ? I know
f = lambda x, y: x + y

Collapse
mandrewcito profile image
Andrés Baamonde Lozano Author

is a function that add two numbers, i store it on a variable. You can use it with f(2, 1)