Python Language Reduce

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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?