How to use the reduce function in Python

1 Answer

0 votes
"""
Demonstration of idiomatic use of reduce() in Python.

Although Python encourages using built‑ins like sum(), max(), or comprehensions,
reduce() is still useful when you want to collapse a sequence into a single value
using a custom rule.

We will:
1. Define a function that uses reduce() to compute the product of numbers.
2. Define a function that uses reduce() to flatten a list of lists.
3. Show how reduce() works step‑by‑step.
"""

from functools import reduce

def multiply_all(numbers):
    """
    Multiply all numbers in a list using reduce().
    The lambda receives the accumulated value and the next element.
    Equivalent to: (((n1 * n2) * n3) * n4) ...
    """
    return reduce(lambda acc, x: acc * x, numbers, 1)  
    # The third argument (1) is the initializer, ensuring correct behavior even for empty lists.


def flatten_list(list_of_lists):
    """
    Flatten a list of lists using reduce().
    Each step concatenates the accumulated list with the next sublist.
    """
    return reduce(lambda acc, lst: acc + lst, list_of_lists, [])
    # Using [] as initializer ensures the accumulator starts as an empty list.


def demo_reduce_steps(numbers):
    """
    Show how reduce() processes elements step-by-step.
    This is purely illustrative.
    """
    def step(acc, x):
        print(f"acc={acc}, next={x} -> new_acc={acc * x}")
        return acc * x

    return reduce(step, numbers, 1)


# ------------------------------
# Usage
# ------------------------------

nums = [2, 3, 4]
nested = [[1, 2], [3], [4, 5]]

product_result = multiply_all(nums)
flattened_result = flatten_list(nested)

print("Product of numbers:", product_result)
print("Flattened list:", flattened_result)

print("\nStep-by-step reduce demonstration:")
demo_reduce_steps(nums)



'''
run:

Product of numbers: 24
Flattened list: [1, 2, 3, 4, 5]

Step-by-step reduce demonstration:
acc=1, next=2 -> new_acc=2
acc=2, next=3 -> new_acc=6
acc=6, next=4 -> new_acc=24

'''

 



answered 11 hours ago by avibootz
...