Python’s reduce function is a great tool to use when you have a sequence (e.g. list, tuples, etc) with multiple items and you have the objective of returning only a single value.
This single value is achieved by combining the results of a function. Simple example are example:
- conducting an operations (e.g. summing or multiplying items with one another)
- comparing the items against each other (e.g. max and min)
The reduce function takes the form:
First let’s demo how it works for operations, let’s say that you have a list:
and we have a function:
Using the reduce function will add up all the items so that a single value remains.
Most of the time the lambda expression is used for reduce rather than defining a function first.
For example rather than defining sum first let’s use lambda directly.
reduce (lambda x,y: x+ y, l)
which will also output:
Using lambda in reduce just like in the map function has the purpose of saving time.
Next let’s demo reduce by comparing the items of a sequence.
Using the same list l:
reduce (lambda x,y: x if (x>y) else y, l)
will output the the highest item value in the list:
If we want to get the minimum then we need to run:
reduce (lambda x,y: x if (x<y) else y, l)
which will output the lowest value in the list:
The reduce function is usually used together with other functions like map and filter.
Now that you get the simple concept of the reduce function, go and challenge yourself by using it to find solutions to complex problems.
For more information go to the official python documentation: