reduce() in Python (original) (raw)
Last Updated : 11 Dec, 2024
The **reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “**functools” module.
Basic Example:
Let’s start with a simple example where we sum up all numbers in a list.
Python `
from functools import reduce
Function to add two numbers
def add(x, y): return x + y
a = [1, 2, 3, 4, 5] res = reduce(add, a)
print(res) # Output: 15
`
**Explanation:
- The reduce() function applies add() cumulatively to the elements in numbers. First, 1 + 2 = 3. Then, 3 + 3 = 6. And so on, until all numbers are processed.
- The final result is 15.
Let’s understand reduce function in detail:
Syntax of reduce()
functools.reduce(function, iterable[, initializer])
- **function: A function that takes two arguments and performs an operation on them.
- **iterable: An iterable whose elements are processed by the function.
- **initializer (optional): A starting value for the operation. If provided, it is placed before the first element in the iterable.
The reduce() function is part of the functools module, so you need to import it before use.
Using reduce() with lambda
When paired with a lambda function, reduce() becomes a concise and powerful tool for aggregation tasks like summing, multiplying or finding the maximum value.
Python `
from functools import reduce
Summing numbers with reduce and lambda
a = [1, 2, 3, 4, 5] res = reduce(lambda x, y: x + y, a)
print(res)
`
**Explanation:
- The lambda function takes two arguments (x and y) and returns their sum.
- reduce() starts by applying the function to the first two elements: 1 + 2 = 3.
- The result (3) is then used with the next element: 3 + 3 = 6, and so on.
- The process continues until all elements are processed, yielding 15.
Using reduce() with operator functions
reduce() can also be combined with operator functions to achieve the similar functionality as with lambda functions and makes the code more readable.
Python `
import functools
importing operator for operator functions
import operator
initializing list
a = [1, 3, 5, 6, 2]
using reduce with add to compute sum of list
print(functools.reduce(operator.add, a))
using reduce with mul to compute product
print(functools.reduce(operator.mul, a))
using reduce with add to concatenate string
print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))
`
Output
17 180 geeksforgeeks
**Explanation:
- operator.add and operator.mul function are predefined operators.
- reduce() applies the add function cumulatively to elements in the list.
- The operation works similarly to the lambda example but the code is cleaner and more readable.
Difference Between reduce() and accumulate()
The accumulate() function from the itertools module also performs cumulative operations, but it returns an iterator containing intermediate results, unlike reduce(), which returns a single final value.
**Example with accumulate:
Python `
from itertools import accumulate from operator import add
Cumulative sum with accumulate
a = [1, 2, 3, 4, 5] res = accumulate(a, add)
print(list(res))
`
Key Differences
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. |