Learning Sections show
Map, Filter, and Reduce in Python
Python provides three powerful functions for functional programming: map()
, filter()
, and reduce()
. These functions allow for efficient and readable data processing operations on iterables.
1. map()
The map()
function applies a given function to all items in an input list (or any other iterable) and returns an iterator of the results.
Example:
# Define a function to square a number
def square(x):
return x**2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
2. filter()
The filter()
function constructs an iterator from elements of an iterable for which a function returns true.
Example:
# Define a function to check if a number is even
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Output: [2, 4]
3. reduce()
The reduce()
function from the functools
module applies a binary function cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single value.
Example:
from functools import reduce
# Define a function to multiply two numbers
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4, 5]
product = reduce(multiply, numbers)
print(product) # Output: 120