Reduce

Sun 25 January 2015

Filed under Python

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 *
1
47
11
47 > 11 --> true
2
47
42
47 > 42 --> true
3
47
102
47 > 102 --> false
4
102
13
102 > 13 --> true

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
1
47
11
47 + 11 --> 58
2
58
42
58 + 42 --> 100
3
100
102
100 + 102 --> 202
4
202
13
202 + 13 --> 215

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)
1
47
11
'4711'
2
'4711'
42
'471142'
3
'471142'
102
'471142102'
4
'471142102'
13
'47114210213'

and the final a is '47114210213' --- so this can be used to concatenate items in a list


Comments


DeeKras.com © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More