๐ Day 98/150 – reduce() Function in Python
The reduce() function is used to repeatedly apply a function to the elements of an iterable until a single value is produced. Unlike map() and filter(), reduce() returns one final result instead of another iterable.
The reduce() function is available in Python's functools module.
Syntax:
from functools import reduceIn this post, we'll explore four common examples of using the reduce() function in Python.
Method 1 – Using reduce() with a Normal Function
Find the sum of all numbers in a list.
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
print(result)
Output
15Explanation
add() takes two numbers and returns their sum.
reduce() repeatedly applies the function to the list.
Calculation:
- (1 + 2) = 3
- (3 + 3) = 6
- (6 + 4) = 10
- (10 + 5) = 15
The final result is 15.
Method 2 – Using reduce() with a Lambda Function
Find the product of all numbers in a list.
120from functools import reduce numbers = [1, 2, 3, 4, 5] result = reduce(lambda x, y: x * y, numbers) print(result)
Output
Explanation
lambda x, y: x * y multiplies two numbers.
reduce() applies the lambda function repeatedly.
Calculation:
(1 × 2) = 2
(2 × 3) = 6
(6 × 4) = 24
(24 × 5) = 120
Method 3 – Find the Maximum Value
Use reduce() to find the largest element in a list.
89from functools import reduce numbers = [12, 45, 7, 89, 23] maximum = reduce(lambda x, y: x if x > y else y, numbers) print(maximum)
Output
Explanation
The lambda function compares two numbers.
It returns the larger one each time.
After all comparisons, the largest value remains.
Method 4 – Taking User Input
Find the sum of numbers entered by the user.
from functools import reduce numbers = list(map(int, input("Enter numbers separated by spaces: ").split())) result = reduce(lambda x, y: x + y, numbers) print("Sum:", result)
Sample Input
10 20 30 40
Output
Sum: 100
Explanation
input()reads the numbers as a string.split()separates them into individual values.map(int, ...)converts each value to an integer.reduce()adds all the numbers and returns a single sum.
Comparison of Methods
| Method | Best For |
|---|---|
| Normal Function | Reusable reduction logic |
| Lambda Function | Short and simple operations |
| Finding Maximum | Comparing elements |
| User Input | Interactive programs |
๐ฅ Key Takeaways
reduce()is available in thefunctoolsmodule.It applies a function repeatedly to reduce an iterable to a single value.
reduce()works with both normal functions and lambda functions.It is commonly used for operations like sum, product, maximum, and minimum.
Unlike
map()andfilter(),reduce()returns a single result instead of an iterable.
Stay tuned for Day 99 of the #150DaysOfPython series! ๐
%20Function%20in%20Python.png)
%20Function%20in%20Python.png)
