Sobes.tech
Junior — Middle

What is the purpose of the reduce function in programming languages?

sobes.tech AI

Answer from AI

The reduce function is used to apply a binary operation sequentially to the elements of an iterable collection, reducing it to a single value. For example, you can sum all elements of a list or multiply them.

In Python, reduce takes a function and an iterable object, then applies the function to the first and second elements, and then applies the result to the third element, and so on, until only one value remains.

Example:

from functools import reduce

numbers = [1, 2, 3, 4]
sum_result = reduce(lambda x, y: x + y, numbers)  # 10
product_result = reduce(lambda x, y: x * y, numbers)  # 24

Thus, reduce allows you to accumulate data from a sequence into a single final value.