Stats

104 Contributors: 3 Thursday, July 21, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Reduce

Syntax

  • reduce(function, iterable[, initializer])

Parameters

ParameterDetails
functionfunction that is used for reducing the iterable (must take two arguments). (positional-only)
iterableiterable that's going to be reduced. (positional-only)
initializerstart-value of the reduction. (optional, positional-only)

Remarks

reduce might be not always the most efficient function. For some types there are equivalent functions or methods:

  • sum() for the sum of a sequence containing addable elements (not strings):

    sum([1,2,3])                                 # = 6
    
  • str.join for the concatenation of strings:

    ''.join(['Hello', ',', ' World'])            # = 'Hello, World'
    
  • next together with a generator could be a short-circuit variant compared to reduce:

    # First falsy item:
    next((i for i in [100, [], 20, 0] if not i)) # = []  
    

Related Examples