Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 BeginneršŸ”µ Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Functional Programming

šŸŽÆ Functional Programming — map, filter, reduce

Process collections elegantly using map, filter, and reduce without explicit loops.


šŸŽÆ The Functional Paradigm

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() — Transform Every Element

`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]

With Lambda

# Simpler with lambda
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, numbers))
print(result)  # [2, 4, 6, 8, 10]

Real-World: Data Transformation

# 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() — Keep Only What You Need

`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]

With Lambda

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]

Real-World: Data Filtering

# 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() — Combine Into One Value

`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)  # 15

How reduce Works

reduce(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) = 15

With Lambda

from functools import reduce

numbers = [1, 2, 3, 4, 5]
total = reduce(lambda a, b: a + b, numbers)
print(total)  # 15

Real-World: Aggregation

from 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}

šŸŽØ Combining map, filter, reduce

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 = 220

šŸ”— Function Composition

Combine 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² = 400

šŸ’” Closures and Higher-Order Functions

Functions 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))  # 15

Real-World: Function Factory

def 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

šŸ“Š Comparison Table

FunctionPurposeReturnsUse When
map()Transform each elementListYou need to convert data
filter()Keep matching elementsListYou need to select data
reduce()Combine into oneSingle valueYou need to aggregate

šŸš€ Advanced Pattern: Pipeline

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)  # 220

āš ļø Readability vs Brevity

Functional 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)

šŸŽÆ When to Use Each

map() — Good For:

  • Converting data types
  • Extracting fields
  • Applying math operations to all elements

filter() — Good For:

  • Selecting subsets
  • Validation
  • Removing unwanted data

reduce() — Good For:

  • Aggregation (sum, product)
  • Finding min/max
  • Building complex objects

List Comprehensions — Even Better For:

  • Most everyday transformations
  • More readable and often faster
  • Pythonic way

šŸ”‘ Key Takeaways

ConceptRemember
map()Transforms each element in a collection
filter()Keeps only elements matching a condition
reduce()Combines all elements into one value
CompositionChain functions for complex transformations
ReadabilitySometimes loops are clearer than functional code
PythonicList comprehensions often better than map/filter

šŸŽ“ Advanced Topics

Ready for more? Explore:

  • **List Comprehensions** — Pythonic alternative to map/filter
  • **Generator Expressions** — Lazy evaluation
  • **functools.partial** — Create specialized functions
  • **itertools** — Advanced iteration tools

šŸ“š What You've Learned

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

Python Docs

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

Courses

PythonFastapiReactJSCloud

Ā© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn