map, filter, reduce
Functional programming utilities
Interview Relevant: Common interview topic
map, filter, reduce
Functional programming tools for data transformation.
Code Examples
Functional programming with map, filter, reduce.
python
1from functools import reduce
2
3nums = [1, 2, 3, 4, 5]
4
5# map - apply function to each element
6squares = list(map(lambda x: x**2, nums))
7# [1, 4, 9, 16, 25]
8
9# filter - keep elements that pass test
10evens = list(filter(lambda x: x % 2 == 0, nums))
11# [2, 4]
12
13# reduce - accumulate to single value
14total = reduce(lambda acc, x: acc + x, nums)
15# 15
16
17# reduce with initial value
18product = reduce(lambda a, b: a * b, nums, 1)
19
20# Comprehension alternatives (often preferred)
21[x**2 for x in nums] # map
22[x for x in nums if x % 2 == 0] # filter