Open In App

reduce() in Python

Last Updated : 11 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

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)

Output
15

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))  

Output
[1, 3, 6, 10, 15]

Key Differences

Featurereduce()accumulate()
Return ValueA single final value (e.g., 15).Intermediate results (e.g., [1, 3, 6, 10, 15]).
Output TypeReturns a single value.Returns an iterator.
Use CaseUseful when only the final result is needed.Useful when tracking cumulative steps.
ImportFrom functools.From itertools.
Suggested Quiz
6 Questions

What is the primary purpose of the reduce() function in Python?

  • A

    To reduce the size of a list

  • B

    To apply a function to items in a list and return a single cumulative result

  • C

    To remove duplicates from a list

  • D

    To filter elements from a list based on a condition

Explanation:

reduce() repeatedly applies a function to the items of an iterable to reduce it to a single value.

Which module must be imported to use reduce() in Python 3?

  • A

    math

  • B

    operator

  • C

    functools

  • D

    itertools

Explanation:


What is the output of the following code?


from functools import reduce

nums = [1, 2, 3, 4]

result = reduce(lambda x, y: x + y, nums)

print(result)

  • A

    10

  • B

    24

  • C

    1234

  • D

    Error

Explanation:

reduce() applies the lambda cumulatively: (((1+2)+3)+4) = 10.

How does the reduce function differ from the map function in Python?

  • A

    Reduce returns a single cumulative value, while map returns an iterable of results

  • B

    Reduce can only work with numeric types, while map can work with any type

  • C

    Reduce applies the function to each element independently, while map combines them

  • D

    Reduce requires an initializer, while map does not

Explanation:


What will this code return?


from functools import reduce


nums = [2, 3, 4]

result = reduce(lambda x, y: x * y, nums)

print(result)

  • A

    24

  • B

    9

  • C

    Error

  • D

    6

Explanation:

Multiplying cumulatively: 2 * 3 = 6, then 6 * 4 = 24.

Which of the following is not true about reduce()?

  • A

    It can only be used with numeric data types

  • B

    It stops execution if the iterable is empty and no initializer is provided

  • C

    It returns a single value after processing all elements

  • D

    It accepts an optional initializer argument

Explanation:

reduce() can be used with any data types, such as strings, as long as the function supports them.

Quiz Completed Successfully
Your Score :   2/6
Accuracy :  0%
Login to View Explanation
1/6 1/6 < Previous Next >

Next Article
Article Tags :
Practice Tags :

Similar Reads