Trusted answers to developer questions

How to use the reduce() method in Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

The reduce() function facilitates a functional approach to Python programming. It performs a rolling-computation as specified by the passed function to the neighboring elements, by taking a function and an iterable as arguments, and returns the final computed value.

Note: A rolling-computation is the one where we compute the required value by going through all of the data starting from the first value, where each new result depends on the last computed result of the previous data.

The reduce() function computation is similar to a for-loop in Python, but being an in-built function, it’s much better and faster.


Syntax

Here is the function signature for the reduce() function in Python:

from functools import reduce
# function signature for the reduce() method
returned_value = reduce(function, iterable)

Note: The reduce() function resides in the functools module which must be imported before the function is called.

As described above, the reduce() function takes the following two arguments as input:

  • function: A valid, pre-defined function. This is a lambda function in most cases.

  • iterable: This is an iterable object (e.g. list, tuple, dictionary).

Returned: A single value gained as a result of applying the function to the iterable’s element.

svg viewer

Examples

Let’s take a look at a couple of examples of how the reduce() method works:

1. Using a lambda function

from functools import reduce
# Returns the sum of all the elements using `reduce`
result = reduce((lambda a, b: a + b), [1, 2, 3, 4])
print(result)

2. Using a pre-defined function

from functools import reduce
# Returns the sum of two elements
def sumTwo(a,b):
return a+b
result = reduce(sumTwo, [1, 2, 3, 4])
print(result)

RELATED TAGS

python
lambda
map
apply
filter
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?