Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reduce in Python
# Docs:
# https://docs.python.org/3/library/functools.html#functools.reduce
import functools
# reduce(function, iterable)
# Applies function to each item of the sequence, left to right.
# Passes two arguments to the function:
# the current total
# the next item in the sequence
print('With named function')
def accumulate(total, value):
return total + value
input = (1, 2, 3)
output = functools.reduce(accumulate, input)
print(output)
print()
print('With lambda')
input = (1, 2, 3)
accumulate = lambda total, value: total + value
output = functools.reduce(accumulate, input)
print(output)
print()
print('With lambda, single line')
input = (1, 2, 3)
output = functools.reduce(lambda total, value: total + value, input)
print(output)
print()
print('Empty sequences are not allowed')
# If the iterable is empty, error
# input = ()
# output = functools.reduce(lambda total, value: total + value, input)
# print(output)
print()
print('Sequence with single item')
# If the iterable contains a single item,
# returns the first item.
input = (42, )
output = functools.reduce(lambda total, value: total + value, input)
print(output)
print()
print('Sequence with initializer')
# If given an initializer, this is placed *before* the items in the sequence
input = (1, 2, 3)
initializer = 100
output = functools.reduce(lambda total, value: total + value, input, initializer)
print(output)
print()
print('Empty sequence with initilizer')
# If the iterable is empty, may pass an initializer.
# The initializer is returned.
input = ()
initializer = 7
output = functools.reduce(lambda total, value: total + value, input, initializer)
print(output)
print()
print('Sequence with single item and initializer')
# If the iterable contains a single item
# and the initializer is given,
# adds the initializer to the single item.
input = (42, )
initializer = 7
output = functools.reduce(lambda total, value: total + value, input, initializer)
print(output)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.