# Tutorial by Examples

## Overview

# No import needed # No import required... from functools import reduce # ... but it can be loaded from the functools module from functools import reduce # mandatory reduce reduces an iterable by applying a function repeatedly on the next element of an iterable and the cumulative resul...

## Using reduce

def multiply(s1, s2): print('{arg1} * {arg2} = {res}'.format(arg1=s1, arg2=s2, res=s1*s2)) return s1 * s2 asequence = [1, 2, 3] Given an initializer the function is started by applying it to the...

## Cumulative product

import operator reduce(operator.mul, [10, 5, -3]) # Out: -150

## Non short-circuit variant of any/all

reduce will not terminate the iteration before the iterable has been completly iterated over so it can be used to create a non short-circuit any() or all() function: import operator # non short-circuit &quot;all&quot; reduce(operator.and_, [False, True, True, True]) # = False # non short-circu...

## First truthy/falsy element of a sequence (or last element if there is none)

# First falsy element or last element if all are truthy: reduce(lambda i, j: i and j, [100, [], 20, 10]) # = [] reduce(lambda i, j: i and j, [100, 50, 20, 10]) # = 10 # First truthy element or last element if all falsy: reduce(lambda i, j: i or j, [100, [], 20, 0]) # = 100 reduce(la...

Page 1 of 1