Python Functional Tools: map(), filter(), reduce()
🧠 What Are map(), filter(), and reduce()?
These are higher-order functions that take another function as an argument and apply it to
a sequence (like a list). They are very useful for functional programming in Python.
🔹 1. map() Function
Purpose: Applies a function to each item in an iterable and returns a map object (which
can be converted to a list, tuple, etc.).
Syntax:
map(function, iterable)
Example:
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared = list(map(square, numbers))
print(squared)
Output:
[1, 4, 9, 16]
Using lambda with map():
numbers = [1, 2, 3]
result = list(map(lambda x: x + 10, numbers))
print(result)
Output:
[11, 12, 13]
🔹 2. filter() Function
Purpose: Filters items from an iterable where the function returns True.
Syntax:
filter(function, iterable)
Example:
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5]
evens = list(filter(is_even, numbers))
print(evens)
Output:
[2, 4]
Using lambda with filter():
numbers = [10, 15, 20, 25]
result = list(filter(lambda x: x > 15, numbers))
print(result)
Output:
[20, 25]
🔹 3. reduce() Function
Purpose: Applies a function cumulatively to the items of an iterable (i.e., reduces it to a
single value).
Must be imported from functools.
Syntax:
from functools import reduce
reduce(function, iterable)
Example:
from functools import reduce
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4]
result = reduce(multiply, numbers)
print(result)
Output:
24
Using lambda with reduce():
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result)
Output:
10
📊 Comparison Table
Function Purpose Returns Typical Use Case
map() Applies a function to map object Transform items in
all items a list
filter() Filters items based filter object Select items meeting
on condition a condition
reduce() Reduces items to a single value Aggregate
single value computation (sum,
product, etc.)