Python22 min read
Python Map Filter Reduce
Understand functional tools map, filter, and reduce, when to use them, and when list comprehensions are clearer.
Michael Brown
September 15, 2025
3.6k72
map, filter, and reduce come from functional programming. They let you process collections in a declarative way.
General idea:
- map → transform
- filter → select
- reduce → combine
## map(): transform items
```python
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
```
Equivalent with list comprehension:
```python
squared = [x ** 2 for x in numbers]
```
## filter(): select items
```python
numbers = [1,2,3,4,5,6,7,8,9,10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
```
Equivalent:
```python
evens = [x for x in numbers if x % 2 == 0]
```
## reduce(): combine items
```python
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
```
## Real examples
```python
names = ["tom", "sarah", "mike"]
upper = list(map(str.upper, names))
words = ["hi", "hello", "hey", "goodbye"]
long_words = list(filter(lambda w: len(w) > 3, words))
nums = [2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(upper, long_words, product)
```
## Graph: data flow
```mermaid
flowchart LR
A[Data] --> B[map: transform]
B --> C[filter: select]
C --> D[reduce: combine]
D --> E[Single result]
```
## Best practice
- Prefer list comprehensions for clarity
- Use reduce only when logic is truly combining
- Keep lambdas simple
In the next lesson, you will master sorting in Python, including custom keys and multi-level sorting.
#Python#Intermediate#Functional