ScanSkill

reduce

This reduce() function applies the function of two arguments cumulatively to the items of iterable, from left to right, and then reduces the iterable to a single value.

Syntax

reduce(function, iterable [, initializer])

Here,

  • function: Required. A function that is of two arguments.
  • iterable: Required. An iterable sequence object.
  • initializer: Optional. A value, placed before the iterable; the default value if the iterable is empty.

Examples

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4])
10 # ((1+2)+3)+4)
>>> reduce(lambda x, y: x-y, [125, 25, 5, 1])
94 # ((125-25)-5)-1)
>>> reduce(lambda x, y: x*y, [2, 2, 2, 2])
16 # ((2*2)*2)*2)
>>> reduce(lambda x, y: x/y, [125, 25, 5, 1])
1 # ((125/25)/5)/1)
>>> reduce(lambda x, y: x*y, [1])
1

Here, the left argument, x, is the accumulated value and the right argument, y, is the updated value from the iterable.

>>> reduce(lambda x, y: x+y, [], 1)
1
>>> reduce(lambda x, y: x+y, [], 0)
0
>>> reduce(lambda x, y: x*y, [1, 2, 3], 0)
0  # ((0*1)*2)*3)