Introduction
In this lesson, we'll delve into three powerful functions provided by Python for functional programming: map(), filter(), and reduce(). These functions are essential for performing transformations, filtering, and aggregations over iterables efficiently. We'll explore how these functions can be used to cleanly replace common loop patterns and give you insight into choosing the appropriate method for different scenarios.
Using map()
The map() function is used to apply a given function to each item of an iterable (like a list or tuple) and return a map object (an iterator).
Syntax
map(function, iterable)
Example
Let's double each number in a list using the map() function:
numbers = [1, 2, 3, 4]
double_function = lambda x: x * 2
doubled_numbers = list(map(double_function, numbers))
# Output:
[2, 4, 6, 8]
Using filter()
The filter() function is used to construct an iterator from elements of an iterable for which a function returns true.
Syntax
filter(function, iterable)
Example
We'll filter out odd numbers from a list:
numbers = [1, 2, 3, 4, 5]
odd_filter = lambda x: x % 2 != 0
odd_numbers = list(filter(odd_filter, numbers))
# Output:
[1, 3, 5]
Using reduce()
The reduce() function, which is available in the functools module, cumulatively applies a function to the items of an iterable to reduce it to a single cumulative value.
Syntax
from functools import reduce
reduce(function, iterable[, initializer])
Example
Let's use reduce() to calculate the factorial of a number:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
factorial = reduce(lambda x, y: x * y, numbers)
# Output:
120
Choosing Between map(), filter(), reduce(), and Other Constructs
- Readability: In Python, readability is a key factor. Although
map(),filter(), andreduce()are powerful, they can make code harder to read compared to list comprehensions and explicit loops, especially when the function logic is complex. - Performance:
map()andfilter()return iterators that may have performance benefits since they do not store results in memory. However, for small input sizes or in IO-bound applications, the differences might be negligible. - List Comprehensions: Often more readable than using
map()orfilter(). Preferred for small to medium-sized data sets.
Example: Comparison
Transforming a list using list comprehension:
doubled_numbers = [x * 2 for x in numbers]
Filtering using list comprehension:
odd_numbers = [x for x in numbers if x % 2 != 0]
Writing Small, Pure Functions
To leverage map(), filter(), and reduce() effectively, write small, pure functions that are easy to test and debug. A pure function is one that has no side effects and returns the same output given the same input.
Example
def is_odd(n):
return n % 2 != 0
odd_numbers = list(filter(is_odd, numbers))
# Output:
[1, 3, 5]
Summary / Key Takeaways
In this lesson on map, filter, and reduce, you have learned:
- map: How to apply a function to every item in an iterable using
map(). - filter: Use
filter()to keep only elements that satisfy a condition. - reduce: Aggregate elements of an iterable into a single value using
functools.reduce(). - Choosing Methods: Consider readability and performance when choosing between map, filter, list comprehensions, and loops.
- Pure Functions: Write small, pure functions to combine effectively with
map(),filter(), andreduce().
