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.
As the name suggests, the reduce()
method reduces any iterable to a single value. The working of the reduce()
method is as follows:
functools.reduce(function, iterable[, initializer])
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.from functools import reducedef concat_string(str1, str2):return str1 + "-" + str2str_list = ["educative", "edpresso", "hi", "hello"]concatenated_string = reduce(concat_string, str_list)print("Concatenated string - " + concatenated_string)
reduce()
method.concat_string
is defined by taking two strings as parameters and concatenates the strings with the -
symbol.str_list
.reduce()
and concat_string
methods to concatenate the strings in str_list
.