
Python
Process collections elegantly using map, filter, and reduce without explicit loops.
Functional programming uses functions to transform data rather than loops:
# Imperative (loops)
squared = []
for x in [1, 2, 3, 4, 5]:
squared.append(x ** 2)
# Functional (map)
squared = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))`map()` applies a function to each element in a collection:
def double(x):
return x * 2
numbers = [1, 2, 3, 4, 5]
result = list(map(double, numbers))
print(result) # [2, 4, 6, 8, 10]# Simpler with lambda
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, numbers))
print(result) # [2, 4, 6, 8, 10]# Convert temperatures
celsius = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # [32.0, 50.0, 68.0, 86.0, 104.0]
# Extract names from dictionaries
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 35}
]
names = list(map(lambda u: u["name"], users))
print(names) # ['Alice', 'Bob', 'Charlie']`filter()` keeps only elements where the function returns True:
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(is_even, numbers))
print(evens) # [2, 4, 6, 8, 10]numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]# Filter users by age
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 17},
{"name": "Charlie", "age": 30}
]
adults = list(filter(lambda u: u["age"] >= 18, users))
# [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
# Keep non-empty strings
words = ["python", "", "coding", "", "rocks"]
filtered = list(filter(None, words)) # None = filter falsy values
print(filtered) # ['python', 'coding', 'rocks']`reduce()` combines all elements into a single value:
from functools import reduce
def add(a, b):
return a + b
numbers = [1, 2, 3, 4, 5]
total = reduce(add, numbers)
print(total) # 15reduce(add, [1, 2, 3, 4, 5])
# Step 1: add(1, 2) = 3
# Step 2: add(3, 3) = 6
# Step 3: add(6, 4) = 10
# Step 4: add(10, 5) = 15from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda a, b: a + b, numbers)
print(total) # 15from functools import reduce
# Product of numbers
numbers = [2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
print(product) # 120
# Find maximum
numbers = [5, 2, 8, 1, 9, 3]
maximum = reduce(lambda a, b: a if a > b else b, numbers)
print(maximum) # 9
# Merge dictionaries
dicts = [
{"a": 1},
{"b": 2},
{"c": 3}
]
merged = reduce(lambda d1, d2: {**d1, **d2}, dicts)
print(merged) # {'a': 1, 'b': 2, 'c': 3}Chain them together for powerful transformations:
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get evens, square them, sum the result
result = reduce(
lambda a, b: a + b,
map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
)
print(result) # 2² + 4² + 6² + 8² + 10² = 4 + 16 + 36 + 64 + 100 = 220Combine multiple functions into one:
def compose(*functions):
"""Apply functions from right to left."""
def composed(x):
for func in reversed(functions):
x = func(x)
return x
return composed
# Create composed function
double = lambda x: x * 2
add_ten = lambda x: x + 10
square = lambda x: x ** 2
process = compose(square, add_ten, double)
result = process(5) # (5 * 2 + 10)² = 20² = 400Functions that return functions:
def multiplier(n):
"""Returns a function that multiplies by n."""
def multiply(x):
return x * n
return multiply
# Create specialized functions
double = multiplier(2)
triple = multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15def make_validator(min_val, max_val):
"""Create a validator function."""
def validate(x):
return min_val <= x <= max_val
return validate
# Create validators
adult_checker = make_validator(18, 120)
grade_checker = make_validator(0, 100)
print(adult_checker(25)) # True
print(adult_checker(15)) # False
print(grade_checker(85)) # True| Function | Purpose | Returns | Use When |
|---|---|---|---|
| map() | Transform each element | List | You need to convert data |
| filter() | Keep matching elements | List | You need to select data |
| reduce() | Combine into one | Single value | You need to aggregate |
from functools import reduce
def pipeline(*functions):
"""Chain functions left to right."""
def execute(x):
return reduce(lambda result, func: func(result), functions, x)
return execute
# Create processing pipeline
numbers = [1, 2, 3, 4, 5]
process = pipeline(
lambda nums: filter(lambda x: x % 2 == 0, nums),
lambda nums: map(lambda x: x ** 2, nums),
lambda nums: reduce(lambda a, b: a + b, nums)
)
result = process(numbers)
print(result) # 220Functional code is powerful but can be hard to read:
# Concise but confusing
result = reduce(lambda a, b: a + b, map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])))
# More readable with intermediate variables
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
squares = map(lambda x: x ** 2, evens)
total = reduce(lambda a, b: a + b, squares)
# Even better with list comprehensions
result = sum(x ** 2 for x in numbers if x % 2 == 0)| Concept | Remember |
|---|---|
| map() | Transforms each element in a collection |
| filter() | Keeps only elements matching a condition |
| reduce() | Combines all elements into one value |
| Composition | Chain functions for complex transformations |
| Readability | Sometimes loops are clearer than functional code |
| Pythonic | List comprehensions often better than map/filter |
Ready for more? Explore:
You now understand:
ā How to transform data with map()
ā How to filter data efficiently
ā How to aggregate with reduce()
ā How to compose functions together
ā When to use functional vs imperative approaches
Ready to practice? Try functional programming challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep ⢠Build Real ⢠Verify Skills ⢠Launch Forward