Python Language Reduce

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

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)) # = []  
    


Got any Python Language Question?