Python

Python reduce() Function

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 item
  • filter() → selects specific items
  • reduce() → combines items into one final result

Important: reduce() is not a built-in function directly available like map() and filter(). It is provided by Python's functools module.

Importing reduce()

Before using reduce(), we need to import it:

from functools import reduce

Basic 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:

15

How does it work?

The operation happens step by step:

1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15

So the final result is:

15

1. Basic Addition Example

from functools import reduce

numbers = [10, 20, 30, 40]

result = reduce(
    lambda a, b: a + b,
    numbers
)

print(result)

Output:

100

reduce() 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:

120

The calculation is:

1 × 2 = 2
2 × 3 = 6
6 × 4 = 24
24 × 5 = 120

3. 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:

50

4. 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:

90

The 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:

10

6. 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:

100

A 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:

20

The calculation starts with 10:

10 + 1 = 11
11 + 2 = 13
13 + 3 = 16
16 + 4 = 20

Syntax

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:

0

Without 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:

120

This represents:

5! = 5 × 4 × 3 × 2 × 1

10. 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:

12

The process is:

Original:
[1, 2, 3, 4, 5, 6]

filter():
[2, 4, 6]

reduce():
2 + 4 + 6 = 12

This 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:

80

12. 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:

8000

This 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:

2000

The calculation is:

100 × 2 = 200
200 × 3 = 600
300 × 4 = 1200

200 + 600 + 1200 = 2000

Here we are combining:

map() → Calculate each item
reduce() → Calculate the final total

14. 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 easy

15. 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:

JavaScript

16. 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:

React

17. 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:

100

18. reduce() with a Set

from functools import reduce

numbers = {10, 20, 30, 40}

result = reduce(
    lambda a, b: a + b,
    numbers
)

print(result)

Output:

100

The 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:

395

We can then calculate the average:

average = total / len(marks)

print(average)

Output:

79.0

20. 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:

130000

21. 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:

55000

This is a good example of using:

map() → Extract/transform data
reduce() → Combine the data

22. map(), filter() and reduce() Together

These three functions can be combined.

Suppose we have:

numbers = [1, 2, 3, 4, 5, 6]

We want to:

  1. Select even numbers
  2. Multiply each by 10
  3. 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:

120

The process is:

Original
[1, 2, 3, 4, 5, 6]

filter()
[2, 4, 6]

map()
[20, 40, 60]

reduce()
20 + 40 + 60

Result
120

This is one of the most important examples to understand.

23. reduce() vs map() vs filter()

FunctionPurposeResult
map()Transform every itemMultiple transformed values
filter()Select matching itemsMultiple selected values
reduce()Combine itemsOne final value

Remember:

map()     → Transform
filter()  → Select
reduce()  → Combine

For example:

map()
[1, 2, 3] → [2, 4, 6]
filter()
[1, 2, 3, 4] → [2, 4]
reduce()
[1, 2, 3, 4] → 10

24. 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 reduce

Then:

reduce(...)

can be used.

The functools module contains functions designed for working with functions and functional-style programming.

Important Points to Remember

  1. reduce() combines multiple values into one value.
  2. reduce() comes from the functools module.
  3. Import it using:
from functools import reduce
  1. Basic syntax:
reduce(function, iterable)
  1. An optional initial value can be provided:
reduce(function, iterable, initializer)
  1. reduce() is useful for totals, products, maximum/minimum values, and cumulative operations.
  2. reduce() can be combined with map() and filter().
  3. reduce() is different from map() and filter() because its main purpose is to produce one final result.

Easy way to remember

map()     → Change
filter()  → Choose
reduce()  → Combine

 

Interactive Sandbox
Python