← Back to Articles
Tutorial

Mastering Python's reduce Function

Learn how to use Python's reduce function with examples and tips.

Paragraph 1: The reduce function in Python is part of the functools module and is used to apply a rolling computation to sequential pairs of values in a list. It is a powerful tool for performing cumulative operations on list items.

Paragraph 2: To use reduce, you must import it from the functools module. The function takes two arguments: a function and an iterable. The function is applied cumulatively to the items in the iterable, reducing the iterable to a single cumulative value. For example, you can use reduce to compute the sum or product of a list of numbers.

Paragraph 3: When using reduce, ensure that the function you pass as the first argument takes two parameters and returns a single result, as this is essential for reduce to work correctly. Using lambda functions can make your code concise, but always ensure they are readable.

Paragraph 4: One common mistake when using reduce is not importing it from the functools module, which will lead to a NameError. Another issue is passing a function that does not correctly handle the cumulative logic or has more than two parameters.

Code Examples

Example 1

from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4])
print(result)  # Output: 10

Example 2

from functools import reduce
def multiply(x, y):
    return x * y
result = reduce(multiply, [1, 2, 3, 4])
print(result)  # Output: 24

More Python Tutorials