Programming Languages

What is the purpose of the reduce function in Python?

Medium
2
Added
The reduce function applies a function of two arguments cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single value.

Solution Code

Programming Languages
from functools import reduce

def add(x, y):
    return x + y

numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
print(result)
Explanation
This code snippet demonstrates how to use the reduce function to accumulate values in a list.

Guided Hints

Import reduce from functools
Define a function to apply
Use reduce to apply the function cumulatively