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:

Let’s understand reduce function in detail:

Syntax of reduce()

functools.reduce(function, iterable[, initializer])

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:

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:

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.