How to use map, filter and reduce?

In Python, map, filter, and reduce are built-in functions that provide powerful tools for working with sequences of data.

map() in Python

The map() function takes a function and an iterable (such as a list) as input and applies the function to each element of the iterable. It returns a new iterable containing the results of applying the function to each element.

numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) # squared will be an iterator containing [1, 4, 9, 16, 25]

filter() in Python

The filter() function takes a function and an iterable, and it returns a new iterable containing only the elements for which the function returns True.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = filter(lambda x: x % 2 == 0, numbers) # evens will be an iterator containing [2, 4, 6, 8, 10]

reduce in Python

The reduce() function is part of the functools module in Python 2, and you need to import it. It applies a binary function (a function that takes two arguments) to the elements of an iterable in a cumulative way. It's used to perform a rolling computation on a sequence of values.

from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) # product will be 120 (1 * 2 * 3 * 4 * 5)

The rule of thumb you use to determine which method you should use is as follows:

  1. If you already have a list of values and you want to do the exact same operation on each of the elements in the array and return the same amount of items in the list, in these type of situations it is better to use the map method.
  2. If you already have list of values but you only want to have items in the array that match certain criteria, in these type of situations it is better to use the filter method.
  3. If you already have list of values, but you want to use the values in that list to create something completely new, in these type of situations it is better to use the reduce method.

Conclusion

These functions provide a functional programming style for manipulating data, making the code more concise and readable. They are especially useful when you need to perform operations on a sequence of elements without writing explicit loops. However, in modern Python, list comprehensions and generator expressions are often preferred over using map, filter, and reduce due to their more readable and Pythonic nature.