Reduce
Reduce
First: What is 'reduce'?
In very short, reduce
applies the function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
The left argument is the accumulated value and the right argument is the update value from the iterable.
The Syntax
reduce(function, iterable)
- The function can be a function or a lambda expression.
-
This function must work on 2 arguments. One is the result of the previous run of the function (the accumulated value). The other is the next item in the iterable.
-
The iterable can be any iterable - list, string, etc.
A few examples:
These examples are for demonstration of reduce
. There are simpler ways to accomplish the same thing that these examples do.
For all these examples, we'll use this iterable: list = [47, 11, 42, 102, 13]
1. reduce((lambda a, b: a if a > b else b), list)
This returns the greatest of all numbers in the list.
The a
is the result of the a > b
. And b
is the next item in the list. If a
is greater than b
, then the value in a
remains in a
, else the value of b
becomes the a
. See below in this chart.
round # | a | b | a>b * |
---|---|---|---|
and the final a
is 102
2. reduce((lambda a,b: a + b), list)
This returns the sum of all numbers in the list.
The a
is the result of the a + b
. And b
is the next item in the list.
round # | a | b | a + b |
---|---|---|---|
and the final a
is 215
3. reduce(lambda a, b: str(a)+str(b), list)
This returns the concatenation of all numbers in the list.
The a
is the result of the str(a)+str(b)
. And b
is the next item in the list.
round # | a | b | str(a)+str(b) |
---|---|---|---|
and the final a
is '47114210213'
--- so this can be used to concatenate items in a list