VOOZH about

URL: https://towardsdatascience.com/using-reduce-in-python-a9c2f0dede54/

⇱ Using Reduce in Python | Towards Data Science


Skip to content

Using Reduce in Python

How to use the reduce function in python

6 min read
👁 Photo by Kevin Ku on Unsplash
Photo by Kevin Ku on Unsplash

Introduction

Python is an object-oriented programming (OOP) language. However, it provides some tools that provide a functional programming style. Some of these tools include the map(), filter(), and reduce() functions. In this tutorial, we will explore the reduce() function and unravel the versatility and usefulness that it provides.


The map() and filter() functions are covered in detail here:

Using Map and Filter in Python


Using a For Loop

The best way to introduce the reduce() function is to start with a problem and attempt to solve it the old-fashioned way, using a for loop. Then we can attempt the same task using the reduce function.

Let’s say that we have a list of numbers and we want to return their product. In other words, we want to multiply all the numbers in the list together and return that single value. We can accomplish this using a for loop:

We have our list of numbers, num_list. We want to multiply the numbers in this list together and get their product. We create the variable product and set it equal to 1. We then loop through num_list using a for loop, and we multiply each number by the result of the previous iteration. After looping through num_list, the product, or the accumulator, will equal 120, which is the product of all the numbers in the list.


Reduce Function

It turns out that we can accomplish the above task using the reduce function instead of a for loop. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable (such as a list). The third argument, which is an initializer, is optional and thus we will discuss it later on.

reduce(function, iterable[, initializer])

Importing Reduce

The reduce function is in the module functools, which contains higher-order functions. Higher-order functions are functions that act on or return other functions. Therefore, in order to use the reduce function, we either need to import the entire functools module, or we can import only the reduce function from functools:

import functools
from functools import reduce

Note: if we import functools, we would need to access the reduce function like so: functools.reduce(arguments). If we import the reduce function only from the functools module, we can access the reduce function by just typing reduce(arguments).


Exploring the Reduce Function

As previously noted, the reduce function takes in two required arguments: a function and an iterable. In order to avoid confusion between the reduce function and the function it takes in as an argument, I will refer to the reduce function as just reduce.

The first argument that reduce takes in, the function, must itself take in two arguments. Reduce will then apply this function cumulatively to the elements of the iterable (from left to right), and reduces it to a single value.


Let’s look at an example:

Let’s say the iterable we use is a list, such as num_list from the above example:

num_list = [1,2,3,4,5]

And the function we use as the first argument for reduce is the following:

def prod(x, y):
 return x * y

This prod function takes in two arguments: x and y. It then returns their product, or x * y.

Let’s pass in the prod function and num_list as our function and iterable, respectively, to reduce:

from functools import reduce
product = reduce(prod, num_list)

Our iterable object is num_list, which is the list: [1,2,3,4,5]. Our function, prod, takes in two arguments, x and y. Reduce will start by taking the first two elements of num_list, 1 and 2, and passes them in to our prod function as the x and y arguments. The prod function returns their product, or 1 2, which equals 2. Reduce will then use this accumulated value of 2 as the new or updated x value, and uses the next element in num_list, which is 3, as our new or updated y value. It then sends these two values (2 and 3) as x and y to our prod function, which then returns their product, 2 3, or 6. This 6 will then be used as our new or updated x value, and the next element in num_list will be used as our new or updated y value, which is 4. It then sends 6 and 4 as our x and y values to the prod function, which returns 24. Thus, our new x value is 24, and our new y value is the next element from num_list, or 5. These two values are passed to the prod function as our x and y values, and prod returns their product, 24 * 5, which equals 120. Thus, reduce took an iterable object, in this case num_list, and reduced it down to a single value, 120. This value is then assigned to the variable product. In other words, the x argument gets updated with the accumulated value, and the y argument gets updated from the iterable.


Iterables and Iterators in Python


Third Argument: Initializer

Remember how we said that reduce can take in an optional third argument, the initializer? The default value for it is None. If we pass in an initializer, it will be used as the first x value by reduce (instead of x being the first element of the iterable). So if we passed in the number 2 in the above example as the initializer:

product = reduce(prod, num_list, 2)
print(product) #240

Then the first two values or arguments for x and y will be 2 and 1, respectively. All subsequent steps will be the same. In other words, the initializer is placed before the elements of our iterable in the calculation.


Using Lambda Expressions

Instead of passing in prod as the function in the above example, we can instead use a lambda expression (or anonymous function) to significantly shorten our code:

product = reduce(lambda x,y: x*y, num_list)

Note how the lambda expression takes in two arguments: x and y, and then returns their product, x*y.

Here is a full tutorial on how to use lambda expressions:

Lambda Expressions in Python


Other Examples of Using Reduce

There are so many other scenarios of when we can use reduce.

For example, we can find the sum of the numbers in a list:

num_list = [1,2,3,4,5]
sum = reduce(lambda x,y: x + y, num_list)
print(sum) #15

Or we can find the maximum number in a list:

num_list = [1,2,3,4,5]
max_num = reduce(lambda x,y: x if x > y else y, num_list)
print(max_num) #5

Or the minimum number in a list:

num_list = [1,2,3,4,5]
min_num = reduce(lambda x,y: x if x < y else y, num_list)
print(min_num) #1

And so many other applications!

Note: Python does have built-in functions such as max(), min(), and sum() that would have been easier to use for these three examples. However, the goal was to show how reduce() can be used to accomplish many different tasks.


If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.

Join Medium with my referral link – Luay Matalka


Conclusion

In this tutorial, we learned how to import and use the reduce function in python. We then saw how lambda expressions can be passed in as an argument to reduce. Lastly, we saw some examples of how reduce can be used.


Written By

Luay Matalka

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.

Write for TDS

Related Articles