../_images/search-banner22.png

Map, Filter, Reduce

map(), filter(), reduce() functions allow to write simpler, shorter code, without the explicit loop, applying a function across a number of iterables:

  • map() apply a function to each element of a given iterable(s).
  • filter() similar with map() but creates a list of elements for which the function returns true.
  • reduce() applies a function of two arguments cumulatively to the elements of an iterable, optionally starting with an initial argument.

map syntax

# returns iterable
map(function, iterables)

map - Compute squares values of a list

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

>>> lst_squared
[1, 4, 9, 16, 25]

map - Convert a list with strings to uppercase

lst = ['marry', 'adolf', 'bob']
lst_upcase = list(map(lambda x: x.upper(), lst))

>>> lst_upcase
['MARRY', 'ADOLF', 'BOB']

map - Element-wise addition of 2 lists

lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
# map can take multiple iterables
lst_add_up = list(map(lambda x,y: x+y, lst1, lst2))

>>> lst_add_up
[11, 22, 33, 44, 55]

# similar with

# using zip and list comprehension
lst_add_up = [x+y for x, y in zip(lst1, lst2)]

>>> lst_add_up
[11, 22, 33, 44, 55]

filter syntax

# returns iterable
filter(boolean_function, iterable)

filter - Get list of even numbers from a range

lst_even = list(filter(lambda x: x % 2 == 0, range(10)))

>>> lst_even
[0, 2, 4, 6, 8]

filter - Get only strings with a length of 3 characters from a list

lst = ['abc', 'efdsaa', 'ftg', 's']
lst_len3 = list(filter(lambda x: len(x) == 3, lst))

>>> lst_len3
['abc', 'ftg']

reduce syntax

reduce(function, iterable[, initial])

reduce - Sum up elements of a list

from functools import reduce

def add(x, y):
    return x + y

lst = [1, 2, 3, 4]
# reduce calls will be: add(1,2), add(3,3), add(6,4)
val = reduce(add, lst)

>>> val
10

reduce - Sum up elements of a list (with an initial value)

from functools import reduce

def add(x, y):
    return x + y

lst = [1, 2, 3, 4]
# reduce calls will be: add(100,1), add(101, 2), add(103, 3), add(106, 4)
val = reduce(add, lst, 100)

>>> val
110