Python's reduce() Function: A Comprehensive Guide
One of the prominent features of Python is its simplicity and to adhere to that, functions have been designed in such a way that the user doesn't have to go through too much of a hassle and can easily write the code.
You must've studied Lists in the previous sections, in this section, you will see how to reduce a list into a single value so make sure to read our article on Lists before going through this.
Reduce() is a function that comes well within the Python features and proves to be a very important asset. It allows us to apply a specified function to a sequence of elements, progressively reducing it to a single value. It may sound a little bit advanced but fear not, it is so simple than almost every chapter of our school mathematics textbook.
In this article, you are going to learn in-depth about reduce() function, its usage, and how it can be applied in Python programs and I will be giving an example program to help you understand it better.
Concept behind reduce() function:
reduce() is one of the many Python functions and is based on the idea of reduction or folding. It is a way to combine or aggregate a sequence of elements into a single value by repeatedly applying a specified function to pairs of elements.
The reduce() function is exceptionally useful when it comes to cumulative calculations and aggregations as it provides a concise and efficient way to reduce it to a single value rather than using iterative loops or explicit functions.
The reduce() function follows a simple algorithm:
- It takes the first two elements of the sequence and applies the specified function to them.
- The result of the previous step becomes the first argument for the following function call, and the next element of the sequence becomes the second argument.
- The function is applied again to the updated arguments, and the process continues until all elements in the sequence have been processed.
- The final output is the accumulated result, which represents the reduction of the entire sequence to a single value.
NOTE: It is important that the reduce() function operates sequentially and processes the elements in a specific order. When the function is not commutative then the order of the sequence impacts the final result so it is important to follow the order.
Syntax of reduce() function:
Before I lurk into the working part, let us first understand the syntax of the reduce() function.
The syntax for using reduce() is as follows:
>>> reduce(function, sequence, initial=None)
Here,
- function: The function to be applied to the elements of the sequence. It should take two arguments and return a single value.
- sequence: The sequence of elements on which the reduction operation will be performed.
- initial (optional): An initial value to be used as the first argument in the reduction operation. If not provided, the first two elements of the sequence will be used as the initial arguments.
The reduce() function works by applying the specified function to the first two elements of the sequence.
How reduce() function works in Python:
The next part of our journey is to understand the working procedure as this will help us to gain more information about the language as well as the function.
Here's a step-by-step breakdown of how reduce() works:
- The syntax, reduce(function, sequence) is called, where function is the specified function and sequence is the sequence of elements.
- The first two elements of the sequence are passed as arguments to the function. These two elements can be either the first two elements of the sequence or an initial value provided as the initial parameter.
- The function returns a result based on the two arguments.
- The result from step 3 becomes the first argument for the following function call, and the next element of the sequence becomes the second argument.
- Steps 3 and 4 are repeated until all elements in the sequence have been processed.
- The final output is the accumulated result, which represents the reduction of the sequence to a single value.
Don't worry if this feels too much as I am going to explain this working procedure with an example to help you understand it further.
Example Program using reduce() function:
Let us create a program where a list of values will be given and I will combine it into a single value using reduce() function.
Sample Program:
>>> from functools import reduce
>>> def combine_values(x, y):
>>> return x + y
>>> my_list = [1, 2, 3, 4, 5]
>>> result = reduce(combine_values, my_list)
>>> print(result)
15
Let's breakdown the above code:
- Firstly, I imported the reduce() function from the functools module.
- Up next, I declared a function that takes two arguments and returns their values. This is the function that the reduce() will use to combine the list.
- Next, I defined a list of values.
- Finally, I used the reduce function to apply the "combine_values" function to the elements of the list. The reduce function will iterate over the list, applying the function to each pair of elements until a single value is obtained.
- Print the result.
To help you grab a hold of this concept, I used a simple program but now let's consider a bit more advanced program.
I will use reduce() function to determine which number is of the maximum value in a list of numbers.
Program:
>>> from functools import reduce
>>> numbers = [10, 50, 40, 60, 70]
>>> max_number = reduce(lambda x, y: x if x > y else y, numbers)
>>> print("Maximum number:", max_number)
Maximum number: 70
In the above example, I defined a lambda function to use the reduce function that iteratively calculates the number of maximum value in the list of numbers.
This is how reduce() function works on a Python program and I hope you got a clear understanding of it.
Concluding Thoughts:
In this journey, I learned about reduce() function, its concept, its syntax, its working nature, and a sample program to get you comfortable with it. I hope you understood the concept clearly and I'll meet you with another intriguing concept of Python and within no time you'll master it.