The reduce() function in Python is used to apply a function to a sequence of elements and return a single value. It is part of the functools module, and takes two arguments: a function and a sequence.
The general syntax of the reduce() function is as follows:
reduce(function, sequence)
Here, function is a function that takes two arguments and returns a value, and sequence is the sequence of elements being reduced.
For example, the following code uses the reduce() function to compute the product of a list of numbers:
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) # Output: 120
In this example, the lambda function lambda x, y: x * y multiplies two numbers, and the reduce() function applies this function to each pair of elements in the numbers list until a single value is returned.
The reduce() function is useful for performing operations on a sequence of elements that result in a single value, such as computing the sum, product, or maximum value of a list. It can also be used with built-in functions like max() and min(). However, since the reduce() function is not a built-in function in Python 3, it must be imported from the functools module before it can be used.
0 Comments