What is the reduce() method in functools module in Python?

What is the functools module in Python?

The functools module in Python allows us to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the function’s scope without modifying or explicitly defining them.

The reduce() method

As the name suggests, the reduce() method reduces any iterable to a single value. The working of the reduce() method is as follows:

  1. We apply the function to the first two elements of the iterable.
  2. We apply the function to the partial result of Step 1 and the third element of the iterable.
  3. The above two steps are repeatedly executed to subsequent elements of the iterable until there are no more elements to be processed.
1 of 3

Method signature

functools.reduce(function, iterable[, initializer])

Parameters

  • function: We apply this function on the elements of the iterable. The function takes two parameters and returns a single value.
  • iterable: This represents the collection of elements to be reduced to a single value.
  • initializer: It’s a value that comes before the iterable’s elements in the computation and acts as a fallback when the iterable is empty.

Code

from functools import reduce
def concat_string(str1, str2):
return str1 + "-" + str2
str_list = ["educative", "edpresso", "hi", "hello"]
concatenated_string = reduce(concat_string, str_list)
print("Concatenated string - " + concatenated_string)

Explanation

  • Line 1: We import the reduce() method.
  • Lines 3–4: A string concatenation method called concat_string is defined by taking two strings as parameters and concatenates the strings with the - symbol.
  • Line 6: We define a list of strings called str_list.
  • Line 8: We use the reduce() and concat_string methods to concatenate the strings in str_list.
  • Line 10: We print the concatenated string.