The reduce function in Python allows us to apply a specific operation to a sequence of elements and reduce them into a single value. It takes two parameters: a function and an iterable object, such as a list or tuple.
Syntax
reduce(function, iterable)
Let's say you have a list of numbers and you want to find their sum. You can use the reduce function to achieve this in a concise manner.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result)
Output
15
In this example, the reduce function takes a lambda function as the first argument, which adds two numbers together. It applies this lambda function cumulatively to the list of numbers, combining them into a single result. In the end, we get the sum of all the numbers.
Let's consider another scenario. Suppose we have a list of numbers and we want to find the maximum value. The reduce function can help us achieve this with ease.
from functools import reduce
numbers = [7, 2, 9, 1, 5]
result = reduce(lambda x, y: x if x > y else y, numbers)
print(result)
Output
9
No comments:
Post a Comment