These are functional programming tools that operate on iterables without explicit loops.
map():
- Applies a function to every item in an iterable
- Returns a map object (iterator)
- Syntax:
map(function, iterable)
filter():
- Filters items based on a condition (function returns True/False)
- Returns a filter object (iterator)
- Syntax:
filter(function, iterable)
reduce():
- Applies a function cumulatively to reduce iterable to a single value
- Must import from
functools module - Syntax:
reduce(function, iterable[, initializer])
Examples:
from functools import reduce
# map() - Transform each element
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# With regular function
def double(x):
return x * 2
doubled = list(map(double, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# Multiple iterables
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = list(map(lambda x, y: x + y, list1, list2))
print(sums) # [5, 7, 9]
# filter() - Select elements based on condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
# Filter strings by length
words = ["hi", "hello", "hey", "wonderful", "world"]
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words) # ['hello', 'wonderful', 'world']
# reduce() - Cumulative operation
numbers = [1, 2, 3, 4, 5]
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all) # 15 (1+2+3+4+5)
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120 (1*2*3*4*5)
# Find maximum
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print(max_value) # 5
# With initial value
sum_with_initial = reduce(lambda x, y: x + y, numbers, 10)
print(sum_with_initial) # 25 (10+1+2+3+4+5)
Comparison with List Comprehensions: