Python6 min read

Python Map, Filter, Reduce

Transform data using map, filter, and reduce functions.

Michael Brown
December 18, 2025
0.0k0

Functional programming basics.

Map

```python # Transform each item numbers = [1, 2, 3, 4, 5]

Using map squared = list(map(lambda x: x ** 2, numbers)) print(squared) # [1, 4, 9, 16, 25]

List comprehension (alternative) squared = [x ** 2 for x in numbers] ```

Filter

```python # Keep items that match condition numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using filter evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4, 6, 8, 10]

List comprehension (alternative) evens = [x for x in numbers if x % 2 == 0] ```

Reduce

```python from functools import reduce

Combine all items into one numbers = [1, 2, 3, 4, 5]

Sum all numbers total = reduce(lambda x, y: x + y, numbers) print(total) # 15

Find maximum maximum = reduce(lambda x, y: x if x > y else y, numbers) print(maximum) # 5 ```

Practical Examples

```python # Convert to uppercase names = ["tom", "sarah", "mike"] upper_names = list(map(str.upper, names)) print(upper_names) # ['TOM', 'SARAH', 'MIKE']

Filter by length words = ["hi", "hello", "hey", "goodbye"] long_words = list(filter(lambda w: len(w) > 3, words)) print(long_words) # ['hello', 'goodbye']

Calculate product from functools import reduce numbers = [2, 3, 4] product = reduce(lambda x, y: x * y, numbers) print(product) # 24 ```

Remember

- map() transforms each item - filter() selects items - reduce() combines into one - List comprehensions often clearer

#Python#Intermediate#Functional