Python Reduce Function with Example Program

This tutorial will help you understand how the Python reduce() function works with example programs.

What is reduce() in Python?

The reduce() in Python is a function that implements mathematical reduction or folding. This function is useful when applying methods on an iterable or reducing the iterable into a single collective value.

Steps of applying Python reduce()

  1. The first step consists of selecting the first two items in the sequence and obtaining the result. 
  2. Next is to apply the same function to the previously obtained result and store it again. 
  3. This procedure continues until there are no remaining elements in the container. 
  4. The final produced result is returned to the console and displayed.

The function (reduce) is popular among Python programmers in the functional programming field.

Along with this, you will learn the possible alternatives of Python reduce that work similarly like reduce().

How does reduce work in python?

In Python, reduce() operates on any iterable and performs the following operations:

  • Employ a function (or user-defined) on the first two iterable elements and produce a partial result.
  • This part of the result is made by putting it together with the third item in the list. 
  • Return a single value that summarizes everything that has occurred until the iterable is empty.

Python reduce() function is intended to take an existing function, apply it to each item in an iterable, and produce a single final output.reduce() is useful for processing iterables without having to write explicit for loops.

Why was reduce removed from Python?

Reduce() was formerly a built-in method (and still is in Python 2.x). However, during the development of Python 3.0, it was relocated to functools.reduce(). The arguments against reduce() include that it is frequently misused, reduces readability, and conflicts with Python’s non-functional viewpoint.

The advent of built-in functions such as sum(), any(), all(), max(), min(), and len() was another reason why reduce() was relocated to functools(). These utilities make common reduce() applications more efficient and readable.

What is the use of reduce() function?

The reduce() function applies a reducer function to each element of an array. It returns a single value, the accumulated result of the function, and skips execution of the function for empty array items. Moreover, the reduce() function in Python does not alter the original array.

Using Operator Functions

This time, let us try the reduce() method with Python’s built-in operator functions. See the following examples for its implementation.

Example 1: Addition

# python code to demonstrate working of reduce()
# using operator functions

# importing functools for reduce()
import functools

# importing operator for operator functions
import operator

# initializing list
lis = [1, 3, 5, 6, 2, ]

# using reduce to compute sum of list
# using operator functions
print("The sum of the list elements is : ", end="")
print(functools.reduce(operator.add, lis))

Output:

The sum of the list elements is : 17

Example 2: Multiplication

# python code to demonstrate working of reduce()
# using operator functions

# importing functools for reduce()
import functools

# importing operator for operator functions
import operator

# initializing list
lis = [1, 3, 5, 6, 2, ]

# using reduce to compute product
# using operator functions
print("The product of list elements is : ", end="")
print(functools.reduce(operator.mul, lis))

Output:

The product of list elements is : 180

Example 3: Concatenation

# python code to demonstrate working of reduce()
# using operator functions

# importing functools for reduce()
import functools

# importing operator for operator functions
import operator

# initializing list
lis = [1, 3, 5, 6, 2, ]

# using reduce to concatenate string
print("The concatenated product is : ", end="")
print(functools.reduce(operator.add, ["Python", "for", "free"]))

Output:

The concatenated product is : Pythonforfree

reduce() can also be employed with operator functions to obtain the same functionality as lambda functions, which simplifies the code.

Either of the given examples works just fine with Python reduce() function. However, always make sure that you have imported the functools and modules that are needed for the function’s proper implementation.

Also read: Linspace Python With Advanced Examples

reduce() vs accumulate()

reduce() and accumulate() are both capable of calculating the sum of a sequence of elements. However, both of them have distinct implementation characteristics.

In the next example, we will compare two programs. One of them will use the Python reduce() function and the other will try the accumulate() function.

Example 1: Using reduce()

# python code to demonstrate summation
# using reduce() and accumulate()
 
# importing itertools for accumulate()
import itertools
 
# importing functools for reduce()
import functools
 
# initializing list
lis = [1, 3, 4, 10, 4]

# printing summation using reduce()
print("The summation of list using reduce is :", end="")
print(functools.reduce(lambda x, y: x+y, lis))

Output:

The summation of list using reduce is :22

The reduce() function reduces the given list and displays a single output.

Remember that this function does not execute empty arguments and does not change the array elements.

Example 2: Using accumulated()

# python code to demonstrate summation
# using reduce() and accumulate()
 
# importing itertools for accumulate()
import itertools
 
# importing functools for reduce()
import functools
 
# initializing list
lis = [1, 3, 4, 10, 4]
 
# printing summation using accumulate()
print("The summation of list using accumulate is :", end="")
print(list(itertools.accumulate(lis, lambda x, y: x+y)))

Output:

The summation of list using accumulate is :[1, 4, 8, 18, 22]

The accumulate() function accepts an iterable target and the function to be executed for each iteration of the target’s value.

In situations when no function is supplied, addition is performed by default. When the input iterable is empty, its output will also be empty.

reduce() function with three parameters

Python 3’s reduce() method supports three parameters in addition to two.

Simply said, reduce() places the third parameter before the value of the second parameter if it exists. Therefore, if the second argument is an empty sequence, the default argument is the third argument.

For example,

# Python program to illustrate sum of two numbers.
def reduce(function, iterable, initializer=None):
	it = iter(iterable)
	if initializer is None:
		value = next(it)
	else:
		value = initializer
	for element in it:
		value = function(value, element)
	return value

# Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.
tup = (2,1,0,2,2,0,0,2)
print(reduce(lambda x, y: x+y, tup,6))

# This code is contributed by aashutoshjha

Output:

15

The Required Arguments: function and iterable

The first argument to reduce() in Python is a two-argument function named function. This function will be used for each item in an iterable in order to calculate a final sum.

Even though the official documentation describes the first argument of reduce() as “a function of two arguments,” any Python callable that accepts two arguments may be passed to reduce(). Callable objects include:

  • classes
  • __call__()
  • instance methods
  • class methods
  • static methods
  • functions.

As its name implies, the second necessary argument, iterable, accepts any Python iterable. This includes all iterable Python objects like:

  • lists
  • tuples
  • range objects
  • generators
  • iterators
  • sets
  • dictionary (keys and values)

To comprehend how the reduce() operates, you will create a function that computes the sum of two values and outputs the equivalent math action.

Example Code

>>> def my_add(a, b):
...     result = a + b
...     print(f"{a} + {b} = {result}")
...     return result

This function computes the sum of a and b, prints an f-string containing the operation, and returns the result of the calculation. See the implementation of how it operates:

>>> my_add(5, 5)
5 + 5 = 10
10

my add() is a two-argument function, so you may provide it together with an iterable to Python’s reduce() to calculate the cumulative total of the iterable’s components.

Examine the following code that uses a number list:

>>> from functools import reduce

>>> numbers = [0, 1, 2, 3, 4]

>>> reduce(my_add, numbers)
# 0 + 1 = 1
# 1 + 2 = 3
# 3 + 3 = 6
# 6 + 4 = 10

Output:

10

When reduce() is used with my add() and numbers as parameters, the output demonstrates all the actions reduce() takes to produce the end result of 10. In this instance, the corresponding operations are ((((0 + 1) + 2) + 3) + 4) = 10.

In the preceding example, the call to reduce() applies my add() to the first two elements of the number (0 and 1) and returns 1. The result is 3 when reduce() calls my add () with the parameters 1 and the next item in numbers, which is 2. The operation is repeated until there are no more elements, at which point reduce() returns 10.

Optional Argument: initializer

The initializer is the third optional argument to the reduce() function in Python. If you provide a value to the initializer, reduce() will pass it to the function’s first call as its first parameter.

This indicates that the first call to the function will utilize the value of the initializer and the first item of its iterable to execute its initial partial calculation. reduce() then continues processing the remaining items of the iterable.

Example: Using my add() with initializer (set to 100)

>>> from functools import reduce

>>> numbers = [0, 1, 2, 3, 4]

>>> reduce(my_add, numbers, 100)

# 100 + 0 = 100
# 100 + 1 = 101
# 101 + 2 = 103
# 103 + 3 = 106
# 106 + 4 = 110
# 110

Output:

110

Since you provide 100 to the initializer, Python’s reduce() uses that number as the first input to my add on the initial call (). Note that in the first iteration, my add() uses 100 and 0 to calculate 100 + 0 = 100 using the first value in the array.

Notably, if you pass a value to the initializer, reduce () will perform one more iteration than it would otherwise.

If you intend to use reduce() to process potentially empty iterables, it is best practice to specify a value in the initializer. When iterable is empty, reduce() will utilize this value as its default return value. If no initializer value is provided, reduce() will throw a TypeError.

Example:

>>> from functools import reduce

>>> # Using an initializer value
>>> reduce(my_add, [], 0)  # Use 0 as return value
0

>>> # Using no initializer value
>>> reduce(my_add, [])  # Raise a TypeError with an empty iterable

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

As shown in this example, reduce() will return the value passed to the initializer if you call it with an empty iterable. When processing empty iterables without an initializer, reduce() will throw a TypeError.

Reducing Iterables With Python’s reduce()

Moving on, the last part of this tutorial presents you with the following:

Summing Numeric Values

The sum use case of Python’s reduce() function is “Hello, World!”. Calculating the cumulative sum of a list of numbers is required. Consider a list of numbers such as [1, 2, 3, 4]. Its sum is 1 plus 2 plus 3 plus 4 equals 10.

Example: Program using for loop

>>> numbers = [1, 2, 3, 4]
>>> total = 0
>>> for num in numbers:
...     total += num
...
>>> total

Output:

10

The for loop iterates over each value in the numbers and totalizes them. In this example, the end result is the sum of all the values, which is 10. In this example, the variable that acts as a sum is called an accumulator.

This is likely the most frequent application of Python’s reduce method (). You have various possibilities for implementing this action using reduce().

Summary

In summary, this Python tutorial has covered everything you need to understand the work of the Python reduce() function.

The implementation of the function was precise in the example along with the explanation given. If you have any clarification, leave a comment below.

Leave a Comment