Bird
Raised Fist0
PythonHow-ToBeginner · 3 min read

How to Use functools.reduce in Python: Simple Guide

Use functools.reduce to apply a function cumulatively to items in a sequence, reducing it to a single value. Import it with from functools import reduce, then call reduce(function, iterable[, initializer]) where function takes two arguments and returns one.
📐

Syntax

The reduce function has this syntax:

  • reduce(function, iterable[, initializer])

function: a function that takes two arguments and returns one value.

iterable: a sequence like a list or tuple to process.

initializer (optional): a starting value used as the first argument to the function.

python
from functools import reduce

result = reduce(function, iterable, initializer)
💻

Example

This example shows how to use reduce to multiply all numbers in a list:

python
from functools import reduce

def multiply(x, y):
    return x * y

numbers = [1, 2, 3, 4]
result = reduce(multiply, numbers)
print(result)
Output
24
⚠️

Common Pitfalls

Common mistakes include:

  • Not importing reduce from functools.
  • Using a function that does not take exactly two arguments.
  • Forgetting the optional initializer when the iterable might be empty.

Example of a wrong and right way:

python
from functools import reduce

# Wrong: function takes one argument only
# def add(x):
#     return x + 1

# Right: function takes two arguments
def add(x, y):
    return x + y

numbers = [1, 2, 3]
result = reduce(add, numbers)
print(result)
Output
6
📊

Quick Reference

ParameterDescription
functionTakes two arguments, returns one value
iterableSequence to reduce
initializerOptional start value for the reduction
✅

Key Takeaways

Import reduce from functools before using it.
The function passed to reduce must take exactly two arguments.
Use reduce to combine all items in an iterable into a single value.
Provide an initializer to avoid errors with empty iterables.
Reduce is useful for operations like sum, product, or custom accumulations.