























Last Updated : 9 Jun, 2026
reduce() function (from the functools module) applies a function cumulatively to the elements of an iterable and returns a single final value. It processes elements step-by-step, combining two elements at a time until only one result remains.
Example: In this example, reduce() combines all strings in a list into one sentence.
Explanation: reduce(lambda x, y: x + " " + y, a) joins elements step-by-step into one string.
reduce(function, iterable[, initializer])
Parameters:
Returns: Returns a single final value after processing all elements.
Example 1: Here, the code adds all numbers in a list using reduce(). The function combines two numbers at a time.
Explanation: reduce(lambda x, y: x + y, a) adds elements step-by-step ((2 + 4) + 6) + 8 = 20.
Example 2: Here, the code finds the largest number from a list using reduce().
Explanation: lambda x, y: x if x > y else y compares two values at each step and keeps the larger one, resulting in the maximum value 12.
Example 3: This example uses functools.reduce() with built-in functions from operator module to perform sum, product and string concatenation on lists.
Output
17 180 geeksforgeeks
Explanation:
accumulate() function (from itertools) and reduce() both apply a function cumulatively to items in a sequence. However, accumulate() returns an iterator of intermediate results, while reduce() returns only final value.
Example: This code demonstrates how accumulate() from itertools module works it performs cumulative operations and returns all intermediate results instead of just a single final value.
Explanation: accumulate(a, add) - Adds elements cumulatively:
Let's understand the difference between accumulate() and reduce() more clearly with the help of the table below:
| Feature | reduce() | accumulate() |
|---|---|---|
| Return Value | A single final value (e.g., 15). |
Intermediate results (e.g., [1, 3, 6, 10, 15]). |
| Output Type | Returns a single value. | Returns an iterator. |
| Use Case | Useful when only the final result is needed. | Useful when tracking cumulative steps. |
| Import | From functools. | From itertools. |
漫思
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。