Miscellaneous

Filter — Map — Reduce

filter function

filter(function, iterable) constructs an iterator from those elements of iterable for which function returns True.

  • iterable may be either a sequence, a container which supports iteration, or an iterator
  • If function is None, the identity function is assumed, that is, all elements ofiterablethat are false are removed

An example:

1
2
3
import numpy as np

array = np.arange(1, 10, dtype=int)
1
2
3
filtered_array = filter(lambda x: x > 3, array)

print(list(filtered_array))
  [4, 5, 6, 7, 8, 9]

map function

map(function, iterable, …) returns an iterator that applies function to every item of iterable, yielding the results

  • If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel
  • With multiple iterables, the iterator stops when the shortest iterable is exhausted

An example:

1
2
3
4
5
import math

mapped_array = map(np.sqrt, array)

print(list(mapped_array))
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]

reduce function

functools.reduce(function, iterable,[initializer]) applies function of two arguments cumulatively to the items of iterable, from left to right, to reduce the iterable to a single value.

  • If the optional initializer is present, it is placed before the items of the iterable in the calculation and serves as a default when the iterable is empty
  • If initializer is not given and iterable contains only one item, the first item is returned

An example:

1
2
3
4
5
6
7
8
from functools import reduce

def reduction_function(x, y):
    print("X:", x, "Y:", y)

    return x + y

reduce(reduction_function, array)
X: 1 Y: 2
X: 3 Y: 3
X: 6 Y: 4
X: 10 Y: 5
X: 15 Y: 6
X: 21 Y: 7
X: 28 Y: 8
X: 36 Y: 9

45

References

Previous