AppDividend
Latest Code Tutorials

Python reduce() Function Explained with Example

0

The reduce() function in Python implements the mathematical technique called folding or reduction. The reduce() method is beneficial when you have to apply a function to an iterable and reduce it to a single cumulative value.

Python reduce()

Python reduce() function is defined under the functools module, which is used to apply specific function passed in its argument to all of the iterable items mentioned in the sequence passed along. The reduce() function works on any iterable and not just on lists.

How reduce() function works in Python?

The reduce() function performs the following steps.

  1. Apply a function (or callable) to the first two elements in the iterable and generate a temporary result.
  2. Use that temporary result, together with the third item in the iterable, to generate another temporary result.
  3. Repeat the process until the iterable is depleted and then return a final single cumulative value.

Syntax

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

Parameters

The reduce() function takes two required parameters and one optional argument.

The first parameter is a function that will take two values from the iterable and generate a temporary result.

The second parameter is iterable, and it can be a list, dictionary, tuple, or any other iterables.

The third parameter is optional, and it takes an initial value that can be processed in the function.

To understand how the reduce() function works, you will write a function that computes the sum of two numbers and prints the equivalent math operation to the screen. Here’s your code.

# app.py

def addition(x, y):
    result = x + y
    print(f"{x} + {y} = {result}")
    return result


addition(11, 19)

Output

python3 app.py
11 + 19 = 30

The addition() function calculates the sum of x and y, prints a message with the operation using an f-string, and returns the result of the cumulative calculations.

Check out the following code that uses a list of numbers, an addition() function, and a reduce() function that returns a single value.

# app.py

from functools import reduce

numbers = [11, 19, 21, 18, 46]


def addition(x, y):
    result = x + y
    return result


print(reduce(addition, numbers))

Output

115

You can see that the list of numbers reduces to a single value, which is the addition of all the list items.

When you call reduce() function, passing addition() function and numbers as arguments, you get an output that shows all the computations that reduce() method performs to reduce it to a single value of 115. In this case, the operations are equivalent to (((((0 + 11) + 19) + 21) + 18) + 46) = 115.

Passing initializer argument

In the above example, we did not pass the initializer argument, which is optional. But let’s pass on this example. We pass 29 as an initial argument and see how it affects our previous output.

# app.py

from functools import reduce

numbers = [11, 19, 21, 18, 46]


def addition(a, b):
    result = a + b
    return result


print(reduce(addition, numbers, 29))

Output

144

If you pass the initializer value, then reduce() function feed it to the first call of function as its first argument.

This means that the first call to the function will use the value of the initializer and the first item of iterable to perform its first temporary computation.

After this, the reduce() function continues working with the subsequent items of iterable.

If you pass the value to the initializer, then the reduce() function will perform one more iteration than it would without an initializer.

Conclusion

Python functools.reduce() is a functional programming function in which iterator values are transformed into a single value using mathematical computation. That is it for the reduce() function example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.