Skip to content
beginner Phase 4 · Python Functional Programming

map, filter, reduce

Apply functional transformations with map, filter, and functools.reduce.

45m
0 problems
Topic Progress 0%

map() Function

Basic map()

# map(function, iterable)
numbers = [1, 2, 3, 4, 5]

# Double each number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # [2, 4, 6, 8, 10]

# Convert to strings
strings = list(map(str, numbers))
print(strings)  # ['1', '2', '3', '4', '5']

# With named function
def square(x):
    return x ** 2

squares = list(map(square, numbers))
print(squares)  # [1, 4, 9, 16, 25]

map() with Multiple Iterables

# map(func, iter1, iter2, ...)
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]

# Add corresponding elements
sums = list(map(lambda x, y: x + y, numbers1, numbers2))
print(sums)  # [11, 22, 33]

# With strings
names = ['Alice', 'Bob']
ages = [30, 25]
info = list(map(lambda n, a: f'{n} is {a}', names, ages))
print(info)  # ['Alice is 30', 'Bob is 25']

# map with zip
result = list(map(lambda x, y: x * y, [1, 2, 3], [4, 5, 6]))
# Equivalent to: [x * y for x, y in zip([1, 2, 3], [4, 5, 6])]

map() vs List Comprehension

numbers = [1, 2, 3, 4, 5]

# map()
doubled = list(map(lambda x: x * 2, numbers))

# List comprehension
doubled = [x * 2 for x in numbers]

# ✅ List comprehension is generally preferred:
# - More readable
# - Can filter in the same expression
# - Better for debugging

# ✅ map() is better when:
# - Using existing function (no lambda needed)
# - Multiple iterables
# - Memory efficiency (lazy evaluation)

# map() is lazy - doesn't create list until consumed
map_obj = map(lambda x: x * 2, numbers)  # No computation yet
list(map_obj)  # Now computes: [2, 4, 6, 8, 10]

filter() Function

Basic filter()

# filter(function, iterable)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Keep even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# Keep positive numbers
mixed = [-5, 3, -1, 8, 0, -2]
positives = list(filter(lambda x: x > 0, mixed))
print(positives)  # [3, 8]

# Keep non-empty strings
words = ['hello', '', 'world', '', 'python']
non_empty = list(filter(None, words))  # None as function
print(non_empty)  # ['hello', 'world', 'python']

filter() with None

# filter(None, iterable) removes falsy values
values = [0, 1, False, True, '', 'hello', None, []]
truthy = list(filter(None, values))
print(truthy)  # [1, True, 'hello']

# Equivalent to:
truthy = [x for x in values if x]

filter() vs List Comprehension

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))

# List comprehension
evens = [x for x in numbers if x % 2 == 0]

# ✅ List comprehension preferred for:
# - Simple filtering
# - Filtering and transforming in one step
# - Readability

# ✅ filter() preferred when:
# - Using existing function
# - Lazy evaluation needed
# - Memory efficiency

reduce() Function

Basic reduce()

from functools import reduce

# reduce(function, iterable[, initializer])
numbers = [1, 2, 3, 4, 5]

# Sum all elements
result = reduce(lambda acc, x: acc + x, numbers)
print(result)  # 15

# With initializer
result = reduce(lambda acc, x: acc + x, numbers, 10)
print(result)  # 25

Common reduce() Patterns

from functools import reduce

# Product of all elements
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda acc, x: acc * x, numbers)
print(product)  # 120

# Find maximum
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_val = reduce(lambda a, b: a if a > b else b, numbers)
print(max_val)  # 9

# Flatten list
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda acc, x: acc + x, nested)
print(flat)  # [1, 2, 3, 4, 5, 6]

# Group by
from collections import defaultdict
words = ['apple', 'banana', 'avocado', 'blueberry']
result = reduce(
    lambda acc, word: acc[word[0]].append(word) or acc,
    words,
    defaultdict(list)
)
print(dict(result))  # {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry']}

reduce() vs Built-in Functions

numbers = [1, 2, 3, 4, 5]

# ✅ Use built-in functions when available
sum(numbers)           # 15 (better than reduce)
max(numbers)           # 9 (better than reduce)
min(numbers)           # 1 (better than reduce)
any(x > 3 for x in numbers)  # True (better than reduce)
all(x > 0 for x in numbers)  # True (better than reduce)

# ✅ Use reduce() for:
# - Custom accumulation logic
# - Complex reductions
# - When no built-in function exists

Chaining Operations

from functools import reduce

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Chain: filter -> map -> reduce
result = reduce(
    lambda acc, x: acc + x,
    map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
)
print(result)  # Sum of squares of even numbers: 4 + 16 + 36 + 64 + 100 = 220

# Equivalent with comprehensions
result = sum(x ** 2 for x in numbers if x % 2 == 0)
print(result)  # 220