map, filter, reduce — Advanced & Practical Notes
1. What are map, filter, reduce?
They are functional programming tools used to process iterables (list, tuple, set, etc.) without explicit
loops.
Function Purpose
map() Transform each element
filter() Select elements based on condition
reduce() Combine all elements into one
2. map() — Transformation Tool
Syntax
map(function, iterable)
Meaning
• Applies function to each element
• Returns a lazy iterator (not a list)
Example
nums = [1, 2, 3, 4]
list(map(lambda x: x*x, nums))
Result: [1, 4, 9, 16]
Advanced Uses
• Multiple iterables
1
map(lambda a, b: a + b, [1,2], [3,4])
Result: [4, 6]
• Type conversion
list(map(int, ['1','2','3']))
3. filter() — Selection Tool
Syntax
filter(function, iterable)
Meaning
• Keeps elements where function returns True
• Returns lazy iterator
Example
nums = [1,2,3,4,5,6]
list(filter(lambda x: x % 2 == 0, nums))
Result: [2, 4, 6]
Advanced Uses
• Remove falsy values
list(filter(None, [0, 1, '', 'hi', False, 3]))
Result: [1, 'hi', 3]
2
4. reduce() — Aggregation Tool
Import (IMPORTANT)
from functools import reduce
Syntax
reduce(function, iterable)
Meaning
• Repeatedly combines elements
• Returns single value
Example
reduce(lambda a, b: a + b, [1,2,3,4])
Result: 10
With Initial Value
reduce(lambda a, b: a * b, [1,2,3], 1)
5. map + filter + reduce (Pipeline 🔥)
nums = [1,2,3,4,5,6]
result = reduce(
lambda a, b: a + b,
map(lambda x: x*x,
filter(lambda x: x % 2 == 0, nums)
)
)
Process: 1. filter → even numbers 2. map → square them 3. reduce → sum
Result: 56
3
6. Lazy Evaluation (Very Important ⚠️)
• map() and filter() do NOT execute immediately
• They compute values only when iterated
m = map(lambda x: x*x, range(5))
No computation yet
7. map/filter vs List Comprehension
Feature map/filter List Comprehension
Readability Medium ⭐ High
Speed Fast Fast
Lazy ✅ Yes ❌ No
Debugging Hard Easy
👉 Python prefers list comprehensions unless laziness is required.
8. When to Use Which? (Industry View)
Use map() when:
• Simple transformation
• Function already exists
Use filter() when:
• Clear condition
• Memory efficiency needed
Use reduce() when:
• Mathematical aggregation
• Custom combining logic
4
9. Common Interview Traps ⚠️
❌ Forgetting list() around map/filter ❌ Forgetting to import reduce ❌ Overusing reduce where
sum()/max() exist
Preferred:
sum(nums)
max(nums)
10. Real-World Examples
Total cart price
reduce(lambda a,b: a+b, map(lambda x: x['price'], cart))
Valid users only
filter(lambda u: u['active'], users)
🧠 One-Line Memory Rule
map = transform
filter = select
reduce = combine
✅ Interview Line
map , filter , and reduce are functional tools that enable clean, lazy, and expressive
data pipelines, but Python often prefers list comprehensions for readability.
🔥 If you understand this, you understand functional programming in Python