Note

Python - reduce() - Reduce an iterable to a single value


Overview of the Python reduce() function. Combine elements from several iterables.

reduce(function, iterable) takes two items at a time from a iterable, applies the function, returns a single result, and repeats until only one result remains. It goes "from left to right".

The reduce() is part of the functools module, so it needs to be imported from functools.

Python reduce() also accepts optional argument default that will be returned if provided iterable is empty.


from functools import reduce

my_list = [1, 3, 5, 7]

my_reduce = reduce(lambda a, b: a**2 + b, my_list)

# Step-by-step:
# 1**2 + 3 = 4
# 4**2 + 5 = 21
# 21**2 + 7 = 448

print(my_reduce)

Output:

448

Using reduce() with an initial value

reduce() accepts optional argument initial. If initial is provided, it is placed before all the items in provided iterable. It also serves as a default if iterable is empty.

from functools import reduce

def merge_words(word_1, word_2):
    return word_1 + '.' + word_2

my_list = ["devcuriosity", "com"]

my_reduce = reduce(merge_words, my_list, "www")

# Step-by-step:
# "www" + "." + "devcuriosity"
# "www.devcuriosity" + "." + "com"

print(my_reduce)

Output:

www.devcuriosity.com

In previous example initial argument was provided last and it was "www".


Using reduce() with an empty iterable and specified initial value

When the iterable is empty, reduce() returns the initial value if provided. This acts as a fallback or default result

from functools import reduce

my_list = []

my_reduce = reduce(lambda a, b: a + b, my_list, "Empty")

print(my_reduce)

Output:

Empty

Key Points to Remember about reduce()

  • "Cumulative" Function Application: reduce() applies a function cumulatively to pairs of elements, producing a single result.

  • initial value: The optional initial value is useful for setting a starting point and for handling empty iterables, preventing errors.

  • Lazy Evaluation: reduce() processes elements only as needed, which makes it efficient for handling large datasets.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: