Table of Contents

    reduce()

    CHAPTER 29.7 · ADVANCED PYTHON FEATURES

    reduce() in Python

    Learn how to combine the values of an iterable into one final result using functools.reduce().

    Some programming problems require a collection of values to be combined into one final result. Examples include calculating a product, finding the largest value, joining text, or merging multiple records.

    Python provides the reduce() function for cumulative operations. It repeatedly combines two values until only one final result remains.

    Learning objective: Learn how reduce() works, how to use named functions and lambda expressions, how the initializer affects processing, and when a built-in function or normal loop is clearer.

    Prerequisites

    What You Should Know

    • Python lists, tuples, and strings
    • Writing and calling functions
    • Function parameters and return values
    • Using lambda expressions
    • Using loops and arithmetic operators
    • Importing functions from Python modules

    What is reduce()?

    reduce() applies a two-argument function cumulatively to the values of an iterable.

    The function first combines two values. It then combines that result with the next value. This process continues until one final value remains.

    Think of reduce() as a funnel

    Many values enter the funnel. They are combined step by step until a single accumulated result comes out.

    Import reduce()

    Unlike map() and filter(), reduce() is not directly available as a built-in function. Import it from the functools module:

    from functools import reduce

    Syntax

    REDUCE SYNTAX
    reduce(function, iterable, initializer)
    reduce(
        function,
        iterable
    )

    The optional initializer can be supplied as the third argument:

    reduce(
        function,
        iterable,
        initializer
    )
    Argument Purpose
    function Accepts two arguments and returns one combined value.
    iterable Supplies the values that will be combined.
    initializer Optionally provides the starting accumulator value.

    Add All Numbers

    from functools import reduce
    
    
    def add_numbers(
        accumulated_value,
        current_value
    ):
        return (
            accumulated_value
            + current_value
        )
    
    
    numbers = [
        1,
        2,
        3,
        4,
        5
    ]
    
    total = reduce(
        add_numbers,
        numbers
    )
    
    print(total)

    Output:

    15

    The cumulative operation can be understood as:

    1 + 2 = 3
    3 + 3 = 6
    6 + 4 = 10
    10 + 5 = 15

    How reduce() Processes Values

    CUMULATIVE PROCESS
    Combine First PairCombine Result with Next ValueFinal Result

    For the list [1, 2, 3, 4], addition proceeds like this:

    ((1 + 2) + 3) + 4

    Use reduce() with lambda

    from functools import reduce
    
    
    numbers = [
        1,
        2,
        3,
        4,
        5
    ]
    
    total = reduce(
        lambda accumulated, current:
            accumulated + current,
        numbers
    )
    
    print(total)

    Output:

    15
    Use lambda only when the cumulative operation is short and clear. Use a named function for complex or reusable reduction logic.

    Multiply All Numbers

    from functools import reduce
    
    
    numbers = [
        1,
        2,
        3,
        4,
        5
    ]
    
    product = reduce(
        lambda accumulated, current:
            accumulated * current,
        numbers
    )
    
    print(product)

    Output:

    120

    The performed calculation is:

    1 * 2 * 3 * 4 * 5 = 120

    Use an Initializer

    The optional initializer becomes the starting accumulated value.

    from functools import reduce
    
    
    numbers = [
        10,
        20,
        30
    ]
    
    total = reduce(
        lambda accumulated, current:
            accumulated + current,
        numbers,
        100
    )
    
    print(total)

    Output:

    160

    The initializer is included at the beginning:

    100 + 10 + 20 + 30 = 160

    Reduce an Empty Iterable

    An initializer allows reduce() to return a result even when the iterable is empty.

    from functools import reduce
    
    
    numbers = []
    
    total = reduce(
        lambda accumulated, current:
            accumulated + current,
        numbers,
        0
    )
    
    print(total)

    Output:

    0
    Important Reducing an empty iterable without an initializer raises a TypeError.

    Find the Largest Value

    from functools import reduce
    
    
    numbers = [
        18,
        42,
        7,
        95,
        31
    ]
    
    largest_number = reduce(
        lambda largest, current:
            largest
            if largest > current
            else current,
        numbers
    )
    
    print(largest_number)

    Output:

    95
    Python already provides max() for this task. Prefer the built-in function when it expresses the requirement more clearly.

    Combine Strings

    from functools import reduce
    
    
    words = [
        "Python",
        "makes",
        "coding",
        "productive"
    ]
    
    sentence = reduce(
        lambda accumulated, current:
            accumulated + " " + current,
        words
    )
    
    print(sentence)

    Output:

    Python makes coding productive
    For ordinary string joining, the string join() method is usually clearer.

    Use Functions from operator

    The operator module provides named functions for common operators.

    from functools import reduce
    from operator import mul
    
    
    numbers = [
        2,
        3,
        4,
        5
    ]
    
    product = reduce(
        mul,
        numbers
    )
    
    print(product)

    Output:

    120

    Practical Example: Calculate Order Total

    from functools import reduce
    
    
    orders = [
        {
            "order_number": "ORD-101",
            "amount": 750
        },
        {
            "order_number": "ORD-102",
            "amount": 1500
        },
        {
            "order_number": "ORD-103",
            "amount": 2200
        }
    ]
    
    def add_order_amount(
        accumulated_total,
        order
    ):
        return (
            accumulated_total
            + order["amount"]
        )
    
    
    order_total = reduce(
        add_order_amount,
        orders,
        0
    )
    
    print(order_total)

    Output:

    4450

    Merge Dictionary Records

    from functools import reduce
    
    
    settings = [
        {
            "theme": "dark"
        },
        {
            "language": "English"
        },
        {
            "notifications": True
        }
    ]
    
    def merge_settings(
        accumulated_settings,
        current_settings
    ):
        return {
            **accumulated_settings,
            **current_settings
        }
    
    
    combined_settings = reduce(
        merge_settings,
        settings,
        {}
    )
    
    print(combined_settings)

    Output:

    {'theme': 'dark', 'language': 'English', 'notifications': True}

    reduce() vs Built-in Functions

    Requirement Preferred Tool
    Add numeric values sum()
    Find the largest value max()
    Find the smallest value min()
    Join strings join()
    Custom cumulative combination reduce()

    reduce() vs accumulate()

    reduce() returns only the final accumulated result. accumulate() produces the intermediate cumulative results.

    reduce()

    from functools import reduce
    
    
    numbers = [
        1,
        2,
        3,
        4
    ]
    
    result = reduce(
        lambda accumulated, current:
            accumulated + current,
        numbers
    )
    
    print(result)

    Output:

    10

    accumulate()

    from itertools import accumulate
    
    
    numbers = [
        1,
        2,
        3,
        4
    ]
    
    results = list(
        accumulate(numbers)
    )
    
    print(results)

    Output:

    [1, 3, 6, 10]

    Common Mistakes

    1

    Forgetting the Import

    Required Import from functools import reduce
    2

    Using a One-Argument Function

    The reduction function must accept two arguments.

    Correct Pattern The function accepts the accumulated result and the current iterable value.
    3

    Reducing an Empty Iterable

    An empty iterable without an initializer cannot provide the first accumulated value.

    Solution Supply a suitable initializer when empty input is possible.
    4

    Using Complex Lambda Logic

    Complicated lambda expressions make cumulative processing difficult to understand.

    Solution Use a descriptive named function or a normal loop.

    Best Practices

    Recommended Practices

    • Import reduce() from functools.
    • Use a two-argument reduction function.
    • Use descriptive names such as accumulator and current_value.
    • Supply an initializer when empty input is possible.
    • Use a named function for complex cumulative logic.
    • Prefer sum(), min(), or max() for their specific operations.
    • Prefer a normal loop when it makes the processing steps clearer.

    Hands-On Practice

    Practice Exercises

    • Add all values in a tuple.
    • Multiply all numbers in a list.
    • Find the smallest value using reduce().
    • Join a list of words into one sentence.
    • Calculate the total amount of customer orders.
    • Use an initializer with an empty list.
    • Merge several configuration dictionaries.
    • Compare the results of reduce() and accumulate().

    Knowledge Check

    1

    Where is reduce() defined?

    It is provided by Python's functools module.

    2

    How many arguments should the function accept?

    The reduction function should accept two arguments.

    3

    What does reduce() normally return?

    It returns one final accumulated value.

    4

    What is the purpose of the initializer?

    It provides the starting accumulated value and supports empty iterables when an appropriate result can be represented.

    reduce() Quick Reference

    from functools import reduce
    
    
    # Use a named function
    result = reduce(
        function,
        iterable
    )
    
    # Use an initializer
    result = reduce(
        function,
        iterable,
        initializer
    )
    
    # Add values
    total = reduce(
        lambda first, second:
            first + second,
        numbers,
        0
    )
    
    # Multiply values
    product = reduce(
        lambda first, second:
            first * second,
        numbers,
        1
    )
    
    # Find the largest value
    largest = reduce(
        lambda first, second:
            first
            if first > second
            else second,
        numbers
    )

    Summary

    What You Learned

    • reduce() is imported from functools.
    • It cumulatively combines iterable values.
    • Its function accepts an accumulator and a current value.
    • The result of one operation becomes the input to the next.
    • The optional initializer provides a starting value.
    • An initializer supports meaningful processing of empty iterables.
    • Built-in functions may be clearer for common reductions.
    • accumulate() is useful when intermediate cumulative results are required.

    Key Takeaway

    Use reduce() when iterable values must be combined cumulatively into one final result and no clearer built-in operation exists. Use an initializer when an explicit starting value or empty-input behavior is required.