Tuesday, February 27, 2024

Reduce function of python

reduce function

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

Input and Output statements in Python

In Python, input and output are handled using built-in functions input() and print(). पायथन में, इनपुट और आउटपुट को अंतर्निहित फ़ंक्शन इनपुट...