On this page

Guided Exercise: Functional Programming in Python

Published on July 6, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

This guided exercise walks you through a realistic data processing scenario — analysing sales transactions — while applying the functional programming concepts you have learned. Unlike a traditional exercise where you are left to solve problems on your own, this is a guided exercise: you follow along as we build the solution step by step. Each step introduces a new functional programming concept, explains why it is used, and shows the code that solves the problem. By the end, you will have a complete, working solution that demonstrates pure functions, recursion, higher‑order functions, function composition, closures, and currying in a cohesive pipeline.


Exercise Scenario​

You are given a dataset of sales transactions from an e‑commerce platform. Each transaction includes the product name, category, quantity sold, unit price, customer name, and purchase date. Your task is to build a data analysis pipeline that:

  1. Adds a calculated total field to each transaction (quantity * price)
  2. Filters out transactions below a configurable threshold
  3. Groups transactions by category
  4. Computes statistics for each category: total revenue, average revenue, and the most expensive product

You will build this solution step by step, applying functional programming techniques at every stage.


The Data​

We start with a list of dictionaries representing transactions.


transactions = [

    {"product": "Laptop", "category": "Electronics", "quantity": 2, "price": 1200.00, "customer": "Alice", "date": "2025-01-15"},

    {"product": "Book", "category": "Books", "quantity": 5, "price": 15.50, "customer": "Bob", "date": "2025-01-16"},

    {"product": "Headphones", "category": "Electronics", "quantity": 3, "price": 75.00, "customer": "Alice", "date": "2025-01-17"},

    {"product": "Desk", "category": "Furniture", "quantity": 1, "price": 450.00, "customer": "Charlie", "date": "2025-01-18"},

    {"product": "Laptop", "category": "Electronics", "quantity": 1, "price": 1200.00, "customer": "Diana", "date": "2025-01-19"},

    {"product": "Book", "category": "Books", "quantity": 3, "price": 12.00, "customer": "Eve", "date": "2025-01-20"},

    {"product": "Monitor", "category": "Electronics", "quantity": 2, "price": 300.00, "customer": "Frank", "date": "2025-01-21"},

    {"product": "Desk", "category": "Furniture", "quantity": 2, "price": 450.00, "customer": "Alice", "date": "2025-01-22"},

    {"product": "Book", "category": "Books", "quantity": 2, "price": 20.00, "customer": "Bob", "date": "2025-01-23"},

    {"product": "Headphones", "category": "Electronics", "quantity": 1, "price": 75.00, "customer": "Charlie", "date": "2025-01-24"}

]

Part 1: Pure Functions​

The first principle of functional programming is to write pure functions — functions that are deterministic and have no side effects. We begin by writing pure functions for data transformation.

Step 1: Calculate the Total Value of a Transaction​

We need to compute quantity * price for each transaction. This is a pure function because it depends only on its input and produces no side effects.


def transaction_total(transaction):

    """Return the total value of a transaction (quantity * price)."""

    return transaction["quantity"] * transaction["price"]

Why this works: This function takes a dictionary, accesses two keys, performs multiplication, and returns the result. It does not modify the input, does not access any global state, and always returns the same value for the same input. This makes it easy to test and reason about.

Step 2: Add a Total Field to a Transaction​

Instead of modifying the original transaction dictionary, we create a new dictionary with the total field added. This preserves immutability.


def add_total(transaction):

    """Return a new transaction dictionary with a 'total' field added."""

    return {**transaction, "total": transaction["quantity"] * transaction["price"]}

Why this works: The {**transaction, "total": ...} syntax creates a new dictionary that includes all key‑value pairs from the original plus the new total field. The original dictionary is unchanged. This is a pure function because it produces a new object without mutating the input.

Step 3: Filter Transactions by a Threshold​

We need to keep only transactions whose total value is at least a specified threshold. This is another pure function.


def filter_by_threshold(transactions, threshold):

    """Return a list of transactions with total >= threshold."""

    return [t for t in transactions if t["total"] >= threshold]

Why this works: This function uses a list comprehension with a conditional expression. It iterates over the input list, checks each transaction's total field against the threshold, and builds a new list containing only the matching transactions. The original list is not modified.

Putting it together: We now have three pure functions. Let's use map() to add totals to all transactions, then use filter_by_threshold() to remove low‑value transactions.


from functools import reduce



# Step 1: Add total to each transaction

transactions_with_total = list(map(add_total, transactions))



# Step 2: Filter by threshold

threshold = 100

filtered_transactions = filter_by_threshold(transactions_with_total, threshold)



# View the result

for t in filtered_transactions:

    print(f"{t['product']}: ${t['total']:.2f}")

Output:


Laptop: $2400.00

Headphones: $225.00

Desk: $450.00

Laptop: $1200.00

Monitor: $600.00

Desk: $900.00

Notice that transactions with a total below $100 have been removed.

Why we use map() : map() applies a function to every element in an iterable and returns an iterator. It is a higher‑order function that abstracts the iteration pattern, making our code more declarative.


Part 2: Recursion​

Recursion allows us to process data structures without loops. Here, we use recursion to process nested transaction data.

Step 4: Flatten Nested Transactions​

Suppose some transactions contain multiple items. We define a nested data structure:


nested_transactions = [

    {"customer": "Alice", "items": [{"product": "Laptop", "price": 1200, "qty": 2}, {"product": "Mouse", "price": 25, "qty": 3}]},

    {"customer": "Bob", "items": [{"product": "Book", "price": 15.50, "qty": 5}]},

    {"customer": "Charlie", "items": [{"product": "Desk", "price": 450, "qty": 1}, {"product": "Chair", "price": 200, "qty": 2}]}

]

We need to flatten this into a list of individual items. A recursive solution is natural because the nesting can be arbitrarily deep.


def flatten_transactions(nested):

    """Flatten nested transactions into a list of individual items."""

    if not nested:

        return []



    first = nested[0]

    customer = first["customer"]

    items = first["items"]



    # Flatten the items of the first transaction

    flattened_items = [

        {"customer": customer, "product": item["product"], "price": item["price"], "quantity": item["qty"]}

        for item in items

    ]



    # Recursively flatten the rest of the transactions

    return flattened_items + flatten_transactions(nested[1:])

Why this works:

The recursion terminates because each call reduces the length of the input list by one.

Step 5: Calculate Total Revenue Recursively​

We can also calculate the total revenue of a flat list of items using recursion.


def total_revenue_recursive(flat_items):

    """Calculate total revenue from a list of flat items."""

    if not flat_items:

        return 0



    first = flat_items[0]

    return first["price"] * first["quantity"] + total_revenue_recursive(flat_items[1:])

Why this works:

This function is pure because it does not modify any state — it simply computes and returns a value.


# Use the recursive functions

flat = flatten_transactions(nested_transactions)

total = total_revenue_recursive(flat)

print(f"Total revenue: ${total:.2f}")

Output:


Total revenue: $4150.50

Part 3: Higher‑Order Functions​

Higher‑order functions take functions as arguments or return them as results. Python's built‑in map(), filter(), and reduce() are classic examples.

Step 6: Group Transactions by Category​

We use itertools.groupby to group transactions by category. groupby requires the data to be sorted by the grouping key.


from itertools import groupby



def group_by_category(transactions):

    """Group transactions by their category field."""

    # Sort by category

    sorted_transactions = sorted(transactions, key=lambda t: t["category"])



    # Group by category

    groups = {}

    for category, group in groupby(sorted_transactions, key=lambda t: t["category"]):

        groups[category] = list(group)



    return groups

Why this works:

Step 7: Compute Category Statistics​

We use reduce() to compute the total revenue per category. reduce() applies a function cumulatively to the items of a sequence, reducing it to a single value.


def total_revenue_by_category(transactions):

    """Compute total revenue for each category."""

    grouped = group_by_category(transactions)

    result = {}



    for category, items in grouped.items():

        # Use reduce to sum the total field

        result[category] = reduce(lambda acc, t: acc + t["total"], items, 0)



    return result

Why this works:


# Compute total revenue by category

revenue_by_category = total_revenue_by_category(filtered_transactions)

print(revenue_by_category)

Output:


{'Electronics': 5025.0, 'Furniture': 1350.0}

Part 4: Function Composition​

Function composition combines multiple functions into a single function. We build a data processing pipeline by composing our pure functions.

Step 8: Define a Composition Helper​

We define a compose() function that chains functions from right to left, and a pipe() function that chains them from left to right. This is a classic functional programming pattern.


from functools import reduce



def compose(*funcs):

    """Compose functions from right to left."""

    def compose_two(f, g):

        return lambda x: f(g(x))

    return reduce(compose_two, funcs, lambda x: x)



def pipe(*funcs):

    """Compose functions from left to right."""

    def pipe_two(f, g):

        return lambda x: g(f(x))

    return reduce(pipe_two, funcs, lambda x: x)

Why this works:

Step 9: Build the Pipeline​

We want a pipeline that:

  1. Adds a total field to each transaction
  2. Filters out transactions below a threshold
  3. Groups by category
  4. Computes the total revenue per category

def create_pipeline(threshold):

    """Create a data processing pipeline with the given threshold."""

    return pipe(

        lambda data: list(map(add_total, data)),  # Step 1

        lambda data: filter_by_threshold(data, threshold),  # Step 2

        group_by_category,  # Step 3

        total_revenue_by_category  # Step 4

    )

Why this works:


# Create a pipeline with threshold 100

pipeline = create_pipeline(100)



# Execute the pipeline

result = pipeline(transactions)

print(result)

Output:


{'Electronics': 5025.0, 'Furniture': 1350.0}

Part 5: Closures​

Closures allow a function to capture state from its enclosing scope. We use a closure to create a configurable analyser that maintains state.

Step 10: Create an Analyser Factory​

We define a factory function that returns a closure with methods for analysing data. The closure captures a threshold and a currency symbol.


def create_analyser(threshold, currency_symbol):

    """Create an analyser closure with configurable threshold and currency."""



    # Captured variables

    local_threshold = threshold

    local_symbol = currency_symbol



    # Public methods

    def analyse(transactions):

        """Analyse transactions using the configured threshold."""

        filtered = filter_by_threshold(transactions, local_threshold)

        total = reduce(lambda acc, t: acc + t["total"], filtered, 0)

        return f"{local_symbol}{total:.2f}"



    def set_threshold(new_threshold):

        """Update the threshold."""

        nonlocal local_threshold

        local_threshold = new_threshold



    def get_threshold():

        """Get the current threshold."""

        return local_threshold



    def set_symbol(new_symbol):

        """Update the currency symbol."""

        nonlocal local_symbol

        local_symbol = new_symbol



    # Return a dictionary of functions (a closure)

    return {

        "analyse": analyse,

        "set_threshold": set_threshold,

        "get_threshold": get_threshold,

        "set_symbol": set_symbol

    }

Why this works:

Step 11: Use the Analyser​


# Create an analyser with threshold 100 and currency symbol '$'

analyser = create_analyser(100, "$")



# Analyse the transactions

print(analyser["analyse"](transactions))  # Output: $5988.50



# Change the threshold to 200

analyser["set_threshold"](200)

print(analyser["analyse"](transactions))  # Output: $5850.00



# Change the currency symbol

analyser["set_symbol"]("€")

print(analyser["analyse"](transactions))  # Output: €5850.00

Why this works: The closure maintains state across calls. When set_threshold is called, it updates the captured local_threshold variable, and subsequent calls to analyse use the new value. The state is encapsulated and cannot be accessed directly — only through the provided methods.


Part 6: Currying​

Currying transforms a function that takes multiple arguments into a sequence of functions that each take a single argument. This enables partial application and function specialisation.

Step 12: Curry a Discount Function​

We define a general‑purpose curry() decorator, then apply it to a discount calculation function.


def curry(func):

    """Transform a function into a curried function."""

    def curried(*args):

        # If enough arguments are provided, call the function

        if len(args) >= func.__code__.co_argcount:

            return func(*args)

        # Otherwise, return a new function that captures the arguments

        return lambda *more: curried(*(args + more))

    return curried



@curry

def apply_discount(rate, total):

    """Apply a discount rate to a total."""

    return total * (1 - rate)

Why this works:

Step 13: Create Specialised Discount Functions​

With the curried apply_discount, we can create specialised functions by fixing the discount rate.


# Create specialised discount functions

ten_percent_off = apply_discount(0.10)

twenty_percent_off = apply_discount(0.20)



# Apply discounts

original_total = 1200.00

print(ten_percent_off(original_total))   # 1080.0

print(twenty_percent_off(original_total)) # 960.0

Why this works: apply_discount(0.10) returns a new function that expects a total argument. This returned function is a closure that captures the discount rate and applies it when called.

Step 14: Apply Discounts to the Dataset​

We can use the specialised discount functions with map() to apply discounts to all transaction totals.


# Get all totals from the filtered transactions

totals = [t["total"] for t in filtered_transactions]



# Apply a 10% discount to all totals

discounted_totals = list(map(ten_percent_off, totals))

print(discounted_totals)

Output:


[2160.0, 202.5, 405.0, 1080.0, 540.0, 810.0]

Part 7: Capstone — Complete Functional Pipeline​

We now bring everything together into a complete, functional data analysis pipeline.

Step 15: Define All Pure Functions​

We define all the pure functions we have built: add_total, filter_by_threshold, group_by_category, and aggregate_category.


from itertools import groupby

from functools import reduce



def add_total(transaction):

    """Add a total field to a transaction."""

    return {**transaction, "total": transaction["quantity"] * transaction["price"]}



def filter_by_threshold(transactions, threshold):

    """Filter transactions by total threshold."""

    return [t for t in transactions if t["total"] >= threshold]



def group_by_category(transactions):

    """Group transactions by category."""

    sorted_t = sorted(transactions, key=lambda t: t["category"])

    groups = {}

    for category, group in groupby(sorted_t, key=lambda t: t["category"]):

        groups[category] = list(group)

    return groups



def aggregate_category(items):

    """Aggregate statistics for a category."""

    total_revenue = reduce(lambda acc, t: acc + t["total"], items, 0)

    avg_revenue = total_revenue / len(items) if items else 0

    most_expensive = max(items, key=lambda t: t["total"])

    return {

        "total_revenue": total_revenue,

        "average_revenue": avg_revenue,

        "most_expensive_product": most_expensive["product"],

        "most_expensive_total": most_expensive["total"]

    }



def aggregate_all_categories(groups):

    """Aggregate statistics for all categories."""

    return {category: aggregate_category(items) for category, items in groups.items()}

Step 16: Compose the Complete Pipeline​

We use pipe() to compose the complete pipeline.


def analyse_sales(transactions, threshold):

    """Complete sales analysis pipeline."""

    pipeline = pipe(

        lambda data: list(map(add_total, data)),

        lambda data: filter_by_threshold(data, threshold),

        group_by_category,

        aggregate_all_categories

    )

    return pipeline(transactions)

Why this works:

Step 17: Execute the Pipeline​


# Run the analysis with threshold 100

result = analyse_sales(transactions, 100)

print(result)

Expected output:


{

    'Electronics': {

        'total_revenue': 5025.0,

        'average_revenue': 838.33,

        'most_expensive_product': 'Laptop',

        'most_expensive_total': 2400.0

    },

    'Furniture': {

        'total_revenue': 1350.0,

        'average_revenue': 675.0,

        'most_expensive_product': 'Desk',

        'most_expensive_total': 900.0

    }

}

Summary of Concepts Practiced​

ConceptStepExplanationPure functions1, 2, 3, 15Functions that are deterministic and have no side effectsRecursion4, 5Processing nested data structures with recursive callsHigher‑order functions6, 7Using map(), filter(), reduce(), and groupbyFunction composition8, 9, 16Combining functions with compose() and pipe()Closures10, 11Functions that capture and maintain state from enclosing scopesCurrying12, 13, 14Transforming multi‑argument functions into chains of unary functions


Running the Complete Code​

Here is the complete, runnable code for the entire guided exercise. You can copy and paste it into a Python file or interactive environment to follow along.


from itertools import groupby

from functools import reduce



# ============================================================================

# DATA

# ============================================================================



transactions = [

    {"product": "Laptop", "category": "Electronics", "quantity": 2, "price": 1200.00, "customer": "Alice", "date": "2025-01-15"},

    {"product": "Book", "category": "Books", "quantity": 5, "price": 15.50, "customer": "Bob", "date": "2025-01-16"},

    {"product": "Headphones", "category": "Electronics", "quantity": 3, "price": 75.00, "customer": "Alice", "date": "2025-01-17"},

    {"product": "Desk", "category": "Furniture", "quantity": 1, "price": 450.00, "customer": "Charlie", "date": "2025-01-18"},

    {"product": "Laptop", "category": "Electronics", "quantity": 1, "price": 1200.00, "customer": "Diana", "date": "2025-01-19"},

    {"product": "Book", "category": "Books", "quantity": 3, "price": 12.00, "customer": "Eve", "date": "2025-01-20"},

    {"product": "Monitor", "category": "Electronics", "quantity": 2, "price": 300.00, "customer": "Frank", "date": "2025-01-21"},

    {"product": "Desk", "category": "Furniture", "quantity": 2, "price": 450.00, "customer": "Alice", "date": "2025-01-22"},

    {"product": "Book", "category": "Books", "quantity": 2, "price": 20.00, "customer": "Bob", "date": "2025-01-23"},

    {"product": "Headphones", "category": "Electronics", "quantity": 1, "price": 75.00, "customer": "Charlie", "date": "2025-01-24"}

]



nested_transactions = [

    {"customer": "Alice", "items": [{"product": "Laptop", "price": 1200, "qty": 2}, {"product": "Mouse", "price": 25, "qty": 3}]},

    {"customer": "Bob", "items": [{"product": "Book", "price": 15.50, "qty": 5}]},

    {"customer": "Charlie", "items": [{"product": "Desk", "price": 450, "qty": 1}, {"product": "Chair", "price": 200, "qty": 2}]}

]



# ============================================================================

# PURE FUNCTIONS

# ============================================================================



def transaction_total(transaction):

    return transaction["quantity"] * transaction["price"]



def add_total(transaction):

    return {**transaction, "total": transaction["quantity"] * transaction["price"]}



def filter_by_threshold(transactions, threshold):

    return [t for t in transactions if t["total"] >= threshold]



def group_by_category(transactions):

    sorted_t = sorted(transactions, key=lambda t: t["category"])

    groups = {}

    for category, group in groupby(sorted_t, key=lambda t: t["category"]):

        groups[category] = list(group)

    return groups



def aggregate_category(items):

    total_revenue = reduce(lambda acc, t: acc + t["total"], items, 0)

    avg_revenue = total_revenue / len(items) if items else 0

    most_expensive = max(items, key=lambda t: t["total"])

    return {

        "total_revenue": total_revenue,

        "average_revenue": avg_revenue,

        "most_expensive_product": most_expensive["product"],

        "most_expensive_total": most_expensive["total"]

    }



def aggregate_all_categories(groups):

    return {category: aggregate_category(items) for category, items in groups.items()}



# ============================================================================

# RECURSION

# ============================================================================



def flatten_transactions(nested):

    if not nested:

        return []

    first = nested[0]

    customer = first["customer"]

    items = first["items"]

    flattened_items = [

        {"customer": customer, "product": item["product"], "price": item["price"], "quantity": item["qty"]}

        for item in items

    ]

    return flattened_items + flatten_transactions(nested[1:])



def total_revenue_recursive(flat_items):

    if not flat_items:

        return 0

    first = flat_items[0]

    return first["price"] * first["quantity"] + total_revenue_recursive(flat_items[1:])



# ============================================================================

# FUNCTION COMPOSITION

# ============================================================================



def compose(*funcs):

    def compose_two(f, g):

        return lambda x: f(g(x))

    return reduce(compose_two, funcs, lambda x: x)



def pipe(*funcs):

    def pipe_two(f, g):

        return lambda x: g(f(x))

    return reduce(pipe_two, funcs, lambda x: x)



# ============================================================================

# CLOSURES

# ============================================================================



def create_analyser(threshold, currency_symbol):

    local_threshold = threshold

    local_symbol = currency_symbol



    def analyse(transactions):

        filtered = filter_by_threshold(transactions, local_threshold)

        total = reduce(lambda acc, t: acc + t["total"], filtered, 0)

        return f"{local_symbol}{total:.2f}"



    def set_threshold(new_threshold):

        nonlocal local_threshold

        local_threshold = new_threshold



    def get_threshold():

        return local_threshold



    def set_symbol(new_symbol):

        nonlocal local_symbol

        local_symbol = new_symbol



    return {

        "analyse": analyse,

        "set_threshold": set_threshold,

        "get_threshold": get_threshold,

        "set_symbol": set_symbol

    }



# ============================================================================

# CURRYING

# ============================================================================



def curry(func):

    def curried(*args):

        if len(args) >= func.__code__.co_argcount:

            return func(*args)

        return lambda *more: curried(*(args + more))

    return curried



@curry

def apply_discount(rate, total):

    return total * (1 - rate)



# ============================================================================

# COMPLETE PIPELINE

# ============================================================================



def analyse_sales(transactions, threshold):

    pipeline = pipe(

        lambda data: list(map(add_total, data)),

        lambda data: filter_by_threshold(data, threshold),

        group_by_category,

        aggregate_all_categories

    )

    return pipeline(transactions)



# ============================================================================

# DEMONSTRATION

# ============================================================================



if __name__ == "__main__":

    print("=" * 60)

    print("DEMONSTRATION")

    print("=" * 60)



    # Pure functions and map/filter

    print("\n--- Pure Functions ---")

    transactions_with_total = list(map(add_total, transactions))

    filtered = filter_by_threshold(transactions_with_total, 100)

    print("Filtered transactions (total >= 100):")

    for t in filtered:

        print(f"  {t['product']}: ${t['total']:.2f}")



    # Recursion

    print("\n--- Recursion ---")

    flat = flatten_transactions(nested_transactions)

    print("Flattened nested transactions:")

    for item in flat:

        print(f"  {item['customer']}: {item['product']} x{item['quantity']}")

    total = total_revenue_recursive(flat)

    print(f"Total revenue from nested transactions: ${total:.2f}")



    # Function composition

    print("\n--- Function Composition (Pipeline) ---")

    pipeline = create_pipeline(100)

    result = pipeline(transactions)

    print("Pipeline result (threshold = 100):")

    for category, stats in result.items():

        print(f"  {category}: ${stats['total_revenue']:.2f}")



    # Closures

    print("\n--- Closures (Analyser Factory) ---")

    analyser = create_analyser(100, "$")

    print(f"Analyse with threshold 100: {analyser['analyse'](transactions)}")

    analyser['set_threshold'](200)

    print(f"Analyse with threshold 200: {analyser['analyse'](transactions)}")

    analyser['set_symbol']("€")

    print(f"Analyse with threshold 200 and € symbol: {analyser['analyse'](transactions)}")



    # Currying

    print("\n--- Currying ---")

    ten_percent_off = apply_discount(0.10)

    print(f"10% off $1200: ${ten_percent_off(1200):.2f}")



    # Complete pipeline

    print("\n--- Complete Functional Pipeline ---")

    final_result = analyse_sales(transactions, 100)

    print("Complete analysis result:")

    for category, stats in final_result.items():

        print(f"  {category}:")

        print(f"    Total revenue: ${stats['total_revenue']:.2f}")

        print(f"    Average revenue: ${stats['average_revenue']:.2f}")

        print(f"    Most expensive product: {stats['most_expensive_product']} (${stats['most_expensive_total']:.2f})")

Conclusion​

You have now completed a guided exercise that applies the core concepts of functional programming in Python. The solution demonstrates:

The complete, runnable code is provided so you can experiment with it, modify the thresholds, add new transformations, and deepen your understanding of functional programming in Python.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Lazy Evaluation

Next

Advanced Python