In Python, map
, filter
, and reduce
are powerful higher-order functions that apply other functions to sequences or iterables. They allow concise and functional-style processing of data.
map()
The map()
function applies a specified function to each item in an iterable (e.g., list, tuple) and returns a new iterable with the results.
Syntax:
map(function, iterable)
- function: A function to apply to each element.
- iterable: The sequence of elements to process.
Example:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Double each number using `map`
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # Output: [2, 4, 6, 8, 10]
filter()
The filter()
function filters elements from an iterable based on a predicate (a function that returns True
or False
). It returns an iterable containing only the elements that satisfy the condition.
Syntax:
filter(predicate, iterable)
- predicate: A function that evaluates to
True
orFalse
. - iterable: The sequence of elements to filter.
Example:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Get only even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4]
Key Notes:
- If the predicate function returns
False
, the element is excluded. - Useful for filtering based on conditions or rules.
reduce()
The reduce()
function reduces a sequence of elements into a single value by repeatedly applying a specified function. It is part of the functools
module.
Syntax:
from functools import reduce
reduce(function, iterable[, initializer])
- function: A function that takes two arguments and reduces them to one.
- iterable: The sequence of elements to process.
- initializer (optional): A starting value for the reduction.
Example:
from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Calculate the sum of the numbers
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 15
Key Notes:
-
The function is applied cumulatively:
- First step:
1 + 2 = 3
- Second step:
3 + 3 = 6
- Third step:
6 + 4 = 10
- Fourth step:
10 + 5 = 15
- First step:
-
Adding an initializer can specify a starting point:
result = reduce(lambda x, y: x + y, numbers, 10) print(result) # Output: 25 (10 + 15)
Example Combining All Three
from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Step 1: Double each number
doubled = map(lambda x: x * 2, numbers)
# Step 2: Filter out numbers greater than 5
filtered = filter(lambda x: x > 5, doubled)
# Step 3: Sum up the filtered numbers
result = reduce(lambda x, y: x + y, filtered)
print(result) # Output: 18 (6 + 8 + 10)
👉 Next tutorial: is vs == in Python