Reduce in Python
The
reduce()
function in Python is a built-in function that allows you to apply a given function to an iterable (e.g. a list or a tuple) and reduce it to a single value. It takes two arguments: the first argument is the function to be applied, and the second argument is the iterable to be reduced. The function is applied to the first two elements of the iterable, and then to the result and the next element, and so on, until the iterable is reduced to a single value. In this lesson, we'll explore how to use
reduce()
in Python and provide some examples.
Using reduce()
The syntax for using
reduce()
is as follows:
from functools import reduce
result = reduce(function, iterable, initializer)
Where:
-
function
: the function to be applied to the iterable. This function should take two arguments and return a single value. -
iterable
: the iterable to be reduced. -
initializer
(optional): an initial value for the reduction. If not provided, the first two elements of the iterable will be used as the initial value.
Here's an example of using
reduce()
to find the sum of a list of integers:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(sum)
This will output
15
, which is the sum of the numbers in the list.
Using reduce() with an Initializer
If you want to provide an initial value for the reduction, you can pass it as the third argument to
reduce()
. Here's an example of using
reduce()
to find the product of a list of integers, starting with an initial value of 1:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers, 1)
print(product)
This will output
120
, which is the product of the numbers in the list.
Conclusion
The
reduce()
function in Python allows you to apply a given function to an iterable and reduce it to a single value. It is a powerful tool for working with lists and other iterables in Python, and can be used to find the sum, product, or any other reduction.Just remember that the function passed as the first argument to
reduce()
must be associative.