Difficulty: Intermediate
Explain lambda functions and functional programming tools: map, filter, and reduce.
Lambda functions are anonymous, single-expression functions defined with the lambda keyword.
Syntax: lambda arguments: expression
Functional programming tools: - map(func, iterable): Apply func to every item, returns iterator - filter(func, iterable): Keep items where func returns True - functools.reduce(func, iterable): Accumulate by applying func cumulatively
In modern Python, list comprehensions are generally preferred over map/filter for readability. reduce was moved to functools because Guido van Rossum felt it was overused.
# Basic lambda
square = lambda x: x 2
print(square(5)) # 25
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 7)) # 10
# Lambda in sorting
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
# Lambda with max/min
people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
oldest = max(people, key=lambda p: p['age'])
print(oldest) # {'name': 'Alice', 'age': 30}
# Immediately invoked lambda
result = (lambda x, y: x + y)(3, 4)
print(result) # 7
Lambdas are best for short, throwaway functions - especially as key arguments for sort(), max(), min(). For anything complex, use a named function.
# map: apply function to each item
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x 2, nums))
print(squared) # [1, 4, 9, 16, 25]
# Equivalent list comprehension (preferred)
squared2 = [x 2 for x in nums]
print(squared2) # [1, 4, 9, 16, 25]
# map with multiple iterables
names = ['alice', 'bob', 'charlie']
greetings = list(map(lambda n: f'Hello, {n.title()}!', names))
print(greetings)
# filter: keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, range(10)))
print(evens) # [0, 2, 4, 6, 8]
# Chaining map and filter
result = list(map(lambda x: x 2, filter(lambda x: x % 2 == 0, range(10))))
print(result) # [0, 4, 16, 36, 64]
# Comprehension equivalent (more readable)
result2 = [x 2 for x in range(10) if x % 2 == 0]
print(result2) # [0, 4, 16, 36, 64]
map() and filter() return iterators (lazy). List comprehensions are usually preferred in Python for readability, but map/filter are useful when passing existing functions.
from functools import reduce
# Sum all numbers
total = reduce(lambda a, b: a + b, [1, 2, 3, 4, 5])
print(total) # 15
# Steps: ((((1+2)+3)+4)+5)
# Find maximum
max_val = reduce(lambda a, b: a if a > b else b, [3, 1, 4, 1, 5, 9])
print(max_val) # 9
# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda a, b: a + b, nested)
print(flat) # [1, 2, 3, 4, 5, 6]
# With initial value
product = reduce(lambda a, b: a * b, [1, 2, 3, 4], 1)
print(product) # 24
# Better alternatives for common reduce patterns
print(sum([1, 2, 3, 4, 5])) # 15 - use sum()
print(max([3, 1, 4, 1, 5, 9])) # 9 - use max()
import math
print(math.prod([1, 2, 3, 4])) # 24 - use math.prod()
reduce() applies a function cumulatively from left to right. For common operations like sum, max, and product, use built-in functions instead.
Lambda, map, filter, reduce, Functional Programming