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