Python reduce() Function


Reduce() was a built-in Python function. Since python 3 it is no longer a built-in. In this tutorial you will learn how to use Python reduce() function. Watch the interactive examples and try the exercises.


Python reduce

Python reduce() function

Python reduce() gets a function of two arguments and a sequence (like a list). It applies the function cumulatively to the items of the sequence, from left to right and returns the result.

If the sequence contains a single item, the function returns the item. If the sequence is empty an error is raised. It is also possible to define an initial item.

reduce Syntax

reduce(function, sequence[, initial])

  • function - the function will be applied to the items in the sequence to compute a final value.
  • sequence - an iterable with at list a single item.
  • initializer (optional) - starting values that will be computed before the sequence.

Python reduce - Explained

  1. At first, the function is called with the first two elements of the sequence.
  2. Next, the function is applied again. The result is used as the first argument, and the next item in the sequence is used as the second argument.
  3. Reduce repeats the process till no more items left in the sequence.
  4. The result is returned.

Python reduce Flow-Chart

Python reduce flow chart

Python reduce Function - Example

In order to get a thorough understanding of the function, lets try to use reduce in order to calculate cumulative sum of multiple integers. Reduce is a natural way to implement this task – we can think about the sum as a cumulative sum. In each iteration, we add the next integer to the current sum. Watch the example below:

# Python reduce function from functools import reduce # importing the function def sum_function(a, b): return a + b my_items = [1, 2, 3, 4, 5] result = reduce(sum_function, my_items) print("The result is ", result)

Python reduce with lambda Function

When using reduce, sometimes it is easier to use a lambda function instead of declaring a function in the regular way. Lambda functions are anonymous functions that are defined without a name. If you don't use the function elsewhere, it might be better to create a lambda function when calling reduce.

For instance, you can calculate the sum of multiple integers, just like the example above, without naming a function. Instead, you can declare a lambda function. Here is an example:

# Python reduce function lambda from functools import reduce # importing the function my_items = [1, 2, 3, 4, 5] result = reduce(lambda a, b: a +b, my_items) print("The result is ", result)

How to Import the reduce Function

If you get an error while trying to use the reduce function that says that the function is not defined, it is probably because you need to import it from functools. reduce() is a built-in function in python 2. Meaning you can call this function without an import. Since Python 3 it is no longer a built-in. In fact, it belongs to the functools module. Therefore, in order to use the reduce function you have to import it from functools. Here is how to import the reduce function:

# How to Import the reduce Function ############ from functools import reduce # importing the function ############ my_items = [1, 2, 3, 4, 5] result = reduce(lambda a, b: a +b, my_items) print("The result is ", result)

Why was Python reduce Removed

Python reduce() built-in was not removed, it was moved into functools module. One of the reasons is that the function isn't considered “Pythonic” style. For many cases code written using reduce() is clearer when written as an accumulation loop.

For instance, let's say you have a nested list (list of lists), and you want to sum all the items in the first index of the inner lists. It might sound complicated at first, however using a for loop it is not so complicated task. Here are two ways to implement the code, one using an accumulation loop and one using a reduce function.

# reduce alternative from functools import reduce my_items = [ [1, 3], [2, 3, 4], [5, 6] ] result_a = 0 for item in my_items: result_a += item[1] print("Result a is", result_a) result_b = reduce(lambda a, b: (0, a[1] + b[1]), my_items)[1] print("Result b is", result_b)

The bottom line is that reduce tends to be complicated, and sometimes it is best to use an accumulation loop as an alternative. That is why the reduce() function is no longer a built-in in Python 3. However, there are trivial cases in which using reduce is a great option. It is up to you - the programmer to decide which is the best solution for each specific case.


Python reduce - Exercise

In this exercise you will practice using Python reduce function. You get as an input a nested list of lists that contain names. Your task is to return a concatenated list, excluding names that begin with the letter “J”. At first try to solve this problem using an accumulation loop. Afterwards implement your code using a lambda function and reduce.

# Python reduce - Exercise from functools import reduce nested_list = [ ["Liam", "Emma", "Johnny"], ["Charlotte", "Josh", "John", "Oliver"], ["Alexander"], ["Jennifer", "Mia"] ] # Your code goes here: