In this article we’ll go through the Python reduce function and it’s uses complete with several examples.
The Python reduce function has the unique ability to perform a function passed as it’s argument on to every single element in a sequence. The reduce function is a part of the functools
, so every time you want to use reduce, you have to import functools
first. functools
comes bundled with python so you don’t have to worry about downloading it separately.
Syntax
The reduce function works on Lists, Sets, Tuples , Dictionaries, range()
and more!
reduce(func, sequence)
Before we proceed to the examples, you should understand how reduce works. Remember, the function that you pass into reduce should always involve two elements.
- The first two elements of the sequence are selected and passed into the argument function.
- For the next step, the result of step 1 and the next element are passed into the argument function.
- This process keeps repeating over and over, with the result of the previous operation and next element being passed into the argument function until no elements remain.
- Final result is displayed on screen.
Argument function
There are many ways to pass a function into the reduce function. You can use the operator
functions for instance. Here are some commonly used ones.
- operator.add – Adds all the elements in the sequence
- operator.sub – Subtracts all the elements in the sequence
- operator.mul – Product of all elements in a sequence
- operator.truediv – Performs the a / b operation across all elements in a sequence
- operator.mod – Performs the a % b operation across all elements in a sequence
Similarly, you can create your own functions to be used instead. Below we’ll recreate some of the operator functions.
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def divide(x,y):
return x / y
We can now pass the add
, subtract
and divide
function calls into the reduce function. See below for examples on both ways of creating functions and how the reduce function works.
Example Set 1
>>> list1 = [2, 5, 3, 1, 8]
>>> functools.reduce(operator.add,list1)
19
>>> list1 = [2, 5, 3, 1, 8]
>>> functools.reduce(operator.mul,list1)
240
>>> list1 = [2, 5, 3, 1, 8]
>>> functools.reduce(operator.truediv,list1)
0.016666666666666666
Example Set 2
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def divide(x,y):
return x / y
list1 = [2, 5, 3, 1, 8]
print(functools.reduce(add,list1))
print(functools.reduce(subtract,list1))
print(functools.reduce(divide,list1))
19
240
0.016666666666666666
This marks the end of the Python reduce Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.
Here’s a link back to the main Python Built-in Functions page.