Reduce Function in Python
Learn via video course
Overview
The reduce() function in python performs functional computation by taking a function and an iterable (e.g., list, tuple, dictionary, etc.) as arguments, and the result is returned after computation (the process of applying the function on the iterable).
The reduce() function in python is defined in the functools module and doesn't return multiple values or any iterator, it just returns a single value as output which is the result of the whole iterable getting reduced to only a single integer or string or boolean.
Introduction to Python Reduce Function
The reduce() function in python takes a pre-defined function and applies it to all the elements in an iterable (e.g., list, tuple, dictionary, etc.) and computes a single-valued result. This single-valued output results from applying the reduce function on the iterable passed as an argument; only a single integer, string, or boolean is returned.
The reduce() is very handy for processing iterables without programming explicit For loops. This reduce() function is similar to a for loop in Python, reduce() is an in-built function and is programmed in C language, which makes it much more optimized and faster.
The reduce() function in python is a part of the functools module, which has to be imported before calling the function in our program. This single value output means that after applying the reduce function on the iterable, only a single integer or string, or boolean is returned.
Syntax of the Reduce function in Python
functools.reduce(function, iterable)
- The first argument in reduce() is a function. This function will be applied to all the elements in an iterable in a cumulative manner to compute the result.
- The second argument is iterable. Iterables are those python objects that can be iterated/looped over, includes like lists, tuples, sets, dictionaries, generators, iterator, etc.
How reduce() Function in Python Works
The reduce() function in python is a part of the functools module and doesn't return multiple values; it just returns a single value.
Steps of how to reduce function works in python:
- The function passed as an argument is applied to the first two elements of the iterable.
- After this, the function is applied to the previously generated result and the next element in the iterable.
- This process continues until the whole iterable is processed.
- The single value is returned as a result of applying the reduce function on the iterable.
Examples of Reduce Function in Python
Example using lambda function (Summing Numeric Values)
In this example, we have defined a lambda function that calculates the sum of two numbers on the passed list as an iterable using the reduce function.
Code:
Output:
The above python program returns the sum of the whole list as a single value result which is calculated by applying the lambda function, which solves the equation (((1+2)+3)+4).
Example using a pre-defined function (Multiplying Numeric Values)
Now, a pre-defined function, product, which returns the product of 2 numbers passed into it, is used as an argument in the reduce function, which is passed along with a list of numbers.
Code:
Output:
We get the result as 210 because the steps followed by the reduce function calculate the result of the following equation(((2x5)x3)x7). First, the multiplication of 2 and 5 is done, and the result of this multiplication is further done with all the other elements of the list one by one.
Example using Operator Functions in python
Sometimes reduce function is implemented along with Operator functions in python. Operator functions are the basic pre-defined mathematical, logical, and bitwise operations combined inside a single module in python named operator. Let's explore how to reduce function is used with operator functions.
Code:
Output:
The above python program first calculates the sum of a given list of numbers named dummy using function operator.add that calculates the sum of 2 numbers at a time which is then used to calculate for the whole list using reduce function. While in the second example, 2 strings present in the list are concatenated together using the operator.concat function, which is reduced into a single string result using reduce function.
Applying Reduce Function to an Empty List
You must wonder what will happen if an empty list is passed as an argument to the reduce function. Let's check it with the help of an example.
Code:
Output:
So we got a Type Error stating that there is no initial value for an empty sequence. This means that in the case of an empty list, a third argument called initializer has to be passed in the reduce function, which will help us counter this error as now the initializer is placed before the items of the iterable while calculating the sum and it is used as default value in case the list is empty.
Reducing Iterables with reduce()
Finding the Maximum and Minimum value
Reduce function in python can calculate Minimum and Maximum values from the iterable by comparing items within the given iterable. The below program includes two different pre-defined functions.
The first function will take two arguments, a and b, and return their minimum, while the second function will use a similar process to return the maximum value.
Code:
Output:
The above program, when executed, first runs the reduce() with mini() and maxi(), to get the minimum and maximum value out of the provided two arguments. The reduce function then iterates over every element of the iterable, compares them in cumulative pairs, and returns the minimum or maximum value.
Checking if All Values Are True
To check whether all values in the given iterable are True or not, we can write a function that takes two arguments and returns True if both arguments are true. If one or both arguments are false, the function will return False.
Code:
Output:
In the first example, all elements in the iterable are one because of which reduce function returns True, while in the second example, only one element is 0, which makes the whole iterable return False as bool(a and b) is used. For this expression to be True, both arguments have to be 1.
Checking if Any Value is True
To check whether any value in the given iterable is True or not, we can write a function that takes two arguments and returns True if either one of the two arguments is true. If both arguments are false, then the function will return False.
Code:
Output:
In the first example, all elements in the iterable are one except one because of which reduce function returns True, while in the second example, all elements are 0, which makes the whole iterable return False.
Difference Between Map and Reduce
After learning about Reduce, you might have gotten confused between reducing and map function. The main difference between these two is that map() is applied to every item of an iterable one at the time, and in a result an iterator is returned.
Lets see how is a map() function implemented
Code:
Output:
In the above program, the map function applies the lambda function to every element in the iterable one by one, and at the end, an iterator is returned. Here, the type of returned list is <class 'map'>.
Reduce() vs Accumulate()
In the itertools module, a function named accumulate() is present, which takes an iterable as an argument. Sometimes, a function is also passed as an optional second argument.
Syntax : itertools.accumulate(iterable)
The accumulate function returns an iterator that consists of accumulated sums of every item in the iterable. So the working of accumulate varies from the reduce function where only a single value is the result.
Code:
Output:
As we can see, the return type is of <class 'itertools.accumulate'> and the iterator returned is a result of the accumulated sums expression [1, (1+2), (1+2+3), (1+2+3+4)].
Reduce VS Python For Loop
A For loop can do the same thing which a reduce function does in Python, so there is no difference in the functionality between these two, but when it comes to the amount of code to be written to implement the same thing, reduce function has a big advantage over traditional python for loop. Let's understand with an example.
Code:
Output:
The above program calculates the sum of all elements present in the nums array. Both for loop and reduce function produce the same correct output. The only difference between the traditional loop and reduce function is that the latter method outperforms them when the list size is very large, as it is optimized and efficient.
Reduce vs Python List Comprehension
Reduce function returns a single value as a result, while a list comprehension, when applied to a list, returns another list.
Sometimes, like flattening a list of lists into a single list, we can use list comprehension. Let's deep dive into this flattening list with the help of an example.
Code:
Output:
In the above program, a 2D list is flattened by using reduce function where the first two lists are combined and a new list is created which is further passed to reduce function along with the successive list.
While in the case of list comprehension, iteration is done for every row in the matrix, and every item in that particular row is returned.
reduce() function with three parameters
As we have already covered a case where an empty list was passed as an argument to the reduce function, a new 3rd argument initializer is used.
To put it in a simple way, reduce() places the 3rd parameter before the value of the second one if it’s present. Thus, if the 2nd argument is an empty sequence, then the 3rd argument serves as the default one.
Code:
Output:
The above program takes initializer = 3 as an argument in the reduce function, and the lambda function calculates the sum of the whole tuple. Still, in this case, the sum will be initialized by the default value of 3, which is the value of the initializer. Therefore the output will be sum of elements in tuple + 3 = 56
Click here, To know more about Empty list in Python.
Conclusion
- Reduce function in python allows us to perform reduction operations on iterables using python callables and lambda functions. reduce() applies a function to the items in an iterable and reduces them to a single cumulative value.
- Python's reduce function performs various common problems like addition or multiplication of numbers in iterables.
- Reduce function is a very popular method in functional programming even though it has been replaced by many pythonic functions like sum(), any(), min() etc.