Skip to content

Python reduce(): How to Reduce Iterables in Python

Python reduce How to Reduce Iterables in Python

In this tutorial, you’ll learn how to use the Python reduce() function to reduce iterables, such as lists. The Python reduce function takes an iterable of any length and a function and returns a single, reduced value. For many common operations, Python now provides simpler ways than using the reduce() function. However, the function provides a significant opportunity to make your code cleaner and more functional.

By the end of this tutorial, you’ll have learned:

  • What the Python reduce() function is and how to use it
  • How to use built-in functions, custom functions, and lambda functions with Python reduce()
  • How to use an initializer to prevent errors
  • Why Python’s reduce() can be replaced using built-in tools
  • When a Python for loop is better than the Python reduce() function

Understanding the Python reduce() Function

The Python reduce() function is part of the functools library, which provides opportunities for functional programming in Python. Prior to Python 3, the function was a built-in function, but was moved into the standard library following the release of Python 3. The function takes a pre-defined function and applies it to every item in an iterable (such as a list or tuple) and returns a single, computed value.

This is why the function is called reduce: it takes an object with more than a single item and reduces each element until only a single element is left.

Let’s take a look at what makes up the Python reduce() function:

# Understanding the Python reduce() Function
from functools import reduce

reduce(
    function,
    iterable,
    initializer=None
)

As you can see from the code block above, the function takes three parameters, two of which are required:

  1. A function, which is used to reduce the elements with
  2. An iterable, to which the function is applied to reduce values, and
  3. An optional initializer, which is placed before all other values

The function works by taking the passed in function and applying it to the first two items. Then, the function is applied to the newly generated element and the next item in the iterable. This process then continues until all items are processed and a single value is returned.

Let’s take a look at an illustrative example:

# Understanding the Process of the reduce() Function
from functools import reduce

value = reduce(lambda a, b: a + b, [1,2,3,4,5])
print(value)

# Returns: 15

The way that this works is by creating the following sequence of addition: ((((1+2)+3)+4)+5). In the expression, first 1 and 2 are added together, then 3 is added to the result, and so on.

In the next section, you’ll learn how to use the Python reduce() function using built-in functions.

How to Use Built-in Functions with Python’s reduce()

In this section, you’ll learn how to use the Python reduce() function using a practical example. To start off, we’ll use a built-in function to reduce a Python list, using the reduce() function.

# Using a Built-in Function with Python reduce()
from functools import reduce
from operator import mul

value = reduce(mul, [1,2,3,4,5])
print(value)

# Returns: 120

In the example above, we used the built-in operator.mul() function which multiples two values together. This can be a great way to multiply all values in a list. Similar to the example we explored earlier, the product is calculated by multiplying each value with the product of the predecessor.

How to Use User-Defined Functions with Python’s reduce()

The power of the reduce() function really shines when it’s used with user-defined functions. This allows you to pass in different behavior compared to built-in functions. For example, if you wanted to find the minimum value in a list of numbers, you could write the following:

# Using Python reduce() to Find the Minimum Value in a List
from functools import reduce

def min(a, b):
    return a if a < b else b

value = reduce(min, [11, 9, 12, 15, 7, 13])
print(value)

# Returns: 7

The function above uses the ternary operator to return the lower of two values.

How to Use Lambda Functions with Python’s reduce()

The real bread and butter of using the Python reduce() function is by passing in anonymous lambda functions. This allows you to explicitly define the function directly within the function. This removes the ambiguity of why the function was defined and where else it might be used. Let’s take a look at an example of how this works:

# Using a Lambda Function with Python's reduce()
from functools import reduce

value = reduce(lambda a, b: a + b, [11, 9, 12, 15, 7, 13])
print(value)

# Returns: 67

How to Use an Initializer in Python’s reduce()

The Python reduce() function allows you to pass in an initializer to pass in an initial value to use. This means that while your list might have a given number of items, the first value will always be the initializer. Let’s see what this looks like:

# Using an Initializer with the Python reduce() Function
from functools import reduce

value = reduce(lambda a, b: a + b, [0,1,2,3,4], 50)
print(value)

# Returns: 60

In this case, rather than starting at 0, the values start at 50 and work their way through the rest of the list.

The benefit of passing in an initializer is that the function will never raise an error, even if an empty sequence is passed in. Let’s take a look at what happens when we pass in an empty list:

# Passing in an Empty Sequence
from functools import reduce

value = reduce(lambda a, b: a + b, [])
print(value)

# Returns: TypeError: reduce() of empty sequence with no initial value

We can see that when an empty sequence is passed in without an initializer, that a TypeError is raised. Let’s see how we can fix that behavior:

# Fixing the TypeError of the Python reduce() Function
from functools import reduce

value = reduce(lambda a, b: a + b, [], 0)
print(value)

# Returns: 0

When to Not Use the Python reduce() Function

While the Python reduce() function provides a lot of opportunity to write functional code, it is often redundant and less readable than other options. In many cases, Python provides functions that can take iterables and reduce them to a single value.

For example, rather than applying the reduce() to add a list of numbers, you can simply pass the list into the sum() function. Let’s take a look at how this works:

# Comparing reduce() to sum()
from functools import reduce

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

# With reduce()
reduce_value = reduce(lambda a, b: a + b, values)

# With sum()
sum_value = sum(values)

The sum() function is significantly cleaner and more understandable. Since introducing Python 3, Python has included many helpful functions to reducing iterables.

Conclusion

In this tutorial, you learned how to use the Python reduce() function. The function allows you to pass in an iterable object, such as a Python list, to reduce it to a single value. The function allows you to work with built-in functions, lambda functions, and user-degined functions. However, it’s not always the best approach and other built-in tools can be a cleaner way of doing things.

Additional Resources

To learn more about related topics, check out the tutorials below:

Tags:

Leave a Reply

Your email address will not be published.