The reduce() function is used to apply a function cumulatively to the items of an iterable and reduce them to a single value.
Unlike:
map()→ transforms each itemfilter()→ selects specific itemsreduce()→ combines items into one final result
Important:
reduce()is not a built-in function directly available likemap()andfilter(). It is provided by Python'sfunctoolsmodule.
Importing reduce()
Before using reduce(), we need to import it:
from functools import reduceBasic Syntax
reduce(function, iterable)For example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(
lambda a, b: a + b,
numbers
)
print(result)Output:
15How does it work?
The operation happens step by step:
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15So the final result is:
151. Basic Addition Example
from functools import reduce
numbers = [10, 20, 30, 40]
result = reduce(
lambda a, b: a + b,
numbers
)
print(result)Output:
100reduce() combines all values into one value.
2. Find the Product of Numbers
We can multiply all numbers together.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(
lambda a, b: a * b,
numbers
)
print(result)Output:
120The calculation is:
1 × 2 = 2
2 × 3 = 6
6 × 4 = 24
24 × 5 = 1203. Find the Sum of Numbers
from functools import reduce
numbers = [5, 10, 15, 20]
total = reduce(
lambda a, b: a + b,
numbers
)
print(total)Output:
504. Find the Maximum Number
We can use reduce() to find the largest number.
from functools import reduce
numbers = [25, 10, 75, 40, 90, 30]
maximum = reduce(
lambda a, b: a if a > b else b,
numbers
)
print(maximum)Output:
90The function compares two values at a time and keeps the larger one.
5. Find the Minimum Number
Similarly, we can find the smallest number.
from functools import reduce
numbers = [25, 10, 75, 40, 90, 30]
minimum = reduce(
lambda a, b: a if a < b else b,
numbers
)
print(minimum)Output:
106. reduce() with a Normal Function
We don't have to use lambda.
from functools import reduce
def add(a, b):
return a + b
numbers = [10, 20, 30, 40]
result = reduce(add, numbers)
print(result)Output:
100A normal function is useful when the operation is complex or needs to be reused.
7. Reduce with an Initial Value
reduce() can accept a third argument called an initializer.
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(
lambda a, b: a + b,
numbers,
10
)
print(result)Output:
20The calculation starts with 10:
10 + 1 = 11
11 + 2 = 13
13 + 3 = 16
16 + 4 = 20Syntax
reduce(function, iterable, initializer)8. Reduce an Empty List with an Initial Value
An initializer becomes particularly useful when the iterable may be empty.
from functools import reduce
numbers = []
result = reduce(
lambda a, b: a + b,
numbers,
0
)
print(result)Output:
0Without the initial value, reducing an empty iterable causes an error.
9. Calculate Factorial
We can calculate a factorial using reduce().
from functools import reduce
numbers = [1, 2, 3, 4, 5]
factorial = reduce(
lambda a, b: a * b,
numbers
)
print(factorial)Output:
120This represents:
5! = 5 × 4 × 3 × 2 × 110. Sum Only Even Numbers
We can combine filter() and reduce().
First, filter the even numbers:
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(
lambda x: x % 2 == 0,
numbers
)
result = reduce(
lambda a, b: a + b,
even_numbers
)
print(result)Output:
12The process is:
Original:
[1, 2, 3, 4, 5, 6]
filter():
[2, 4, 6]
reduce():
2 + 4 + 6 = 12This demonstrates how filter() and reduce() can work together.
11. Find the Largest Even Number
We can combine filter() and reduce() again.
from functools import reduce
numbers = [10, 25, 30, 45, 50, 65, 80]
even_numbers = filter(
lambda x: x % 2 == 0,
numbers
)
largest = reduce(
lambda a, b: a if a > b else b,
even_numbers
)
print(largest)Output:
8012. Calculate Total Price
Suppose we have product prices:
from functools import reduce
prices = [1000, 2500, 3000, 1500]
total = reduce(
lambda a, b: a + b,
prices
)
print(total)Output:
8000This can be useful for calculating a shopping cart total.
13. Calculate Total with Quantity
Suppose we have:
prices = [100, 200, 300]
quantity = [2, 3, 4]First calculate each item's total:
from functools import reduce
prices = [100, 200, 300]
quantity = [2, 3, 4]
item_totals = map(
lambda price, qty: price * qty,
prices,
quantity
)
total = reduce(
lambda a, b: a + b,
item_totals
)
print(total)Output:
2000The calculation is:
100 × 2 = 200
200 × 3 = 600
300 × 4 = 1200
200 + 600 + 1200 = 2000Here we are combining:
map() → Calculate each item
reduce() → Calculate the final total14. Join Strings
reduce() can also work with strings.
from functools import reduce
words = ["Python", "is", "easy"]
result = reduce(
lambda a, b: a + " " + b,
words
)
print(result)Output:
Python is easy15. Find the Longest Word
from functools import reduce
words = ["Python", "JavaScript", "Django", "React"]
longest = reduce(
lambda a, b: a if len(a) > len(b) else b,
words
)
print(longest)Output:
JavaScript16. Find the Shortest Word
from functools import reduce
words = ["Python", "JavaScript", "Django", "React"]
shortest = reduce(
lambda a, b: a if len(a) < len(b) else b,
words
)
print(shortest)Output:
React17. reduce() with Tuple
reduce() works with tuples as well.
from functools import reduce
numbers = (10, 20, 30, 40)
result = reduce(
lambda a, b: a + b,
numbers
)
print(result)Output:
10018. reduce() with a Set
from functools import reduce
numbers = {10, 20, 30, 40}
result = reduce(
lambda a, b: a + b,
numbers
)
print(result)Output:
100The order of values in a set should not be relied upon, although addition gives the same final total here.
19. Practical Example : Student Marks
Suppose we have marks:
from functools import reduce
marks = [75, 80, 65, 90, 85]
total = reduce(
lambda a, b: a + b,
marks
)
print(total)Output:
395We can then calculate the average:
average = total / len(marks)
print(average)Output:
79.020. Practical Example : Employee Salaries
from functools import reduce
salaries = [25000, 30000, 35000, 40000]
total_salary = reduce(
lambda a, b: a + b,
salaries
)
print(total_salary)Output:
13000021. Practical Example : Course Prices
Suppose SkillMantra has several courses:
from functools import reduce
courses = [
{"name": "Python", "price": 15000},
{"name": "Django", "price": 18000},
{"name": "MERN", "price": 22000}
]First, extract the prices using map():
prices = map(
lambda course: course["price"],
courses
)Then calculate the total using reduce():
total = reduce(
lambda a, b: a + b,
prices
)
print(total)Output:
55000This is a good example of using:
map() → Extract/transform data
reduce() → Combine the data22. map(), filter() and reduce() Together
These three functions can be combined.
Suppose we have:
numbers = [1, 2, 3, 4, 5, 6]We want to:
- Select even numbers
- Multiply each by
10 - Add all the results
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(
lambda x: x % 2 == 0,
numbers
)
multiplied = map(
lambda x: x * 10,
even_numbers
)
total = reduce(
lambda a, b: a + b,
multiplied
)
print(total)Output:
120The process is:
Original
[1, 2, 3, 4, 5, 6]
filter()
[2, 4, 6]
map()
[20, 40, 60]
reduce()
20 + 40 + 60
Result
120This is one of the most important examples to understand.
23. reduce() vs map() vs filter()
| Function | Purpose | Result |
|---|---|---|
map() | Transform every item | Multiple transformed values |
filter() | Select matching items | Multiple selected values |
reduce() | Combine items | One final value |
Remember:
map() → Transform
filter() → Select
reduce() → CombineFor example:
map()
[1, 2, 3] → [2, 4, 6]filter()
[1, 2, 3, 4] → [2, 4]reduce()
[1, 2, 3, 4] → 1024. Why Is reduce() Imported from functools?
Unlike map() and filter(), reduce() is not available directly as a built-in function.
This will work:
map(...)
filter(...)But for reduce() we need:
from functools import reduceThen:
reduce(...)can be used.
The functools module contains functions designed for working with functions and functional-style programming.
Important Points to Remember
reduce()combines multiple values into one value.reduce()comes from thefunctoolsmodule.- Import it using:
from functools import reduce- Basic syntax:
reduce(function, iterable)- An optional initial value can be provided:
reduce(function, iterable, initializer)reduce()is useful for totals, products, maximum/minimum values, and cumulative operations.reduce()can be combined withmap()andfilter().reduce()is different frommap()andfilter()because its main purpose is to produce one final result.
Easy way to remember
map() → Change
filter() → Choose
reduce() → Combine