Python

Constant dripping wears away a stone

map(), filter(), and reduce() functions


  • map(function, iterable(s)): Takes one item from the iterable each time and executes the function for the item until the iterable is exhausted. Then it returns an iterator. If there are more than one iterable, the function must have the same number of parameters as the number of iterables and all iterables must have the same number of items. Each time it takes one item from each iterable and execute the function until all the iterables are exhausted.
    • One Iterable:
    • More than One Iterable:
  • filter(function, iterable): Takes one item from the iterable each time and executes the function for the item until the iterable is exhausted. The items that satisfy the function conditions are kept in the returned iterator.
  • functools.reduce(function, iterable[, initializer]): It is a Python built-in function in modulefunctools. Before using this function, the module needs to be imported into your program first by using import functools. If usefrom functools import reduce, the syntax will bereduce(function, iterable[, initializer]). It takes the first two items from the iterable as the arguments to the function and executes the function. Then it does the same thing using the result that the function returns from using the first two items and the third item in the iterable. It repeats doing this until the iterable is exhausted. Then a single value will be returned. If an initializer exists, it will take the initializer and the first item in the iterable as the arguments to the function and execute the function. The rest is the same as the case without an initializer.
    • Without an Initializer: .
    • With an Initializer: