Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active February 7, 2021 22:09
Show Gist options
  • Save rpivo/e8621baead4e57411c30e7124e295654 to your computer and use it in GitHub Desktop.
Save rpivo/e8621baead4e57411c30e7124e295654 to your computer and use it in GitHub Desktop.
Using reduce in Python

Using reduce in Python

from functools import reduce

print(
  reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
)

# 15

reduce needs to first be imported from functools.

The first argument of reduce is a function that represents the callback that will be called on each item within an iterable. This function takes in two arguments. The first argument (x in the lambda function above example) is the accumulator, and the second argument (y in the above example) is the current item being processed in the iterable.

The second argument for reduce is the iterable that the lambda will operate on. This is [1, 2, 3, 4, 5] in the above example.

You can also pass in a named function in place of the lambda:

def add(a, b):
  return a + b

print(
  reduce(add, [1, 2, 3, 4, 5])
)

# 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment