Learn Functools Reduce Method in 7 Easy Ways

Hello Geeks, Welcome back to another article. Today in this article, we will learn about Python FuncTools reduce method. But before that, we will see why we use the FuncTools module and then discuss the reduce() function within that module. At the end of the article, we will see several examples to understand the module better. So, let’s get started.

FuncTools Module

FuncTools module gives us the functionality of creating higher-order functions that work on other functions. These higher-order functions either return other functions or act on them to extend the function’s scope without changing them or defining them explicitly. These extensions are done with the help of the following function.

Currently, functools contain these 11 functions.

  1. cmp_to_key()
  2. cached_property()
  3. lru_catch()
  4. partial()
  5. partialmethod()
  6. reduce()
  7. singledispatch()
  8. singledispatchmethod()
  9. total_ordering()
  10. update_wrapper()
  11. wraps()

In this article, we will be having a detailed discussion over the functools reduce method of the functools module.

functools.reduce(function, sequence[,initial])

This function is used to get a single value result by solving a sequence on a two-argument function. You can think of it as we pass the first two elements of the sequence to the function and then the resulting work as the first argument for the second iteration. The third element of the sequence acts as the function’s second argument. This will work from left to right in the sequence until all the sequence elements are covered. However, if you want some other initials, then one can specify it using the third argument of the function, which is optional. Let’s see some examples.

Example 1: Applying reduce method on a two Argument Function

from functools import reduce

def multiply_the_sequence(num1,num2):
  return (num1 * num2)

product = reduce(multiply_the_sequence,[1,2,3,4,5])
print(product)

Output:

120

Explanation

So in the above example, we will multiply a list of sequences by applying the reduce method to the sequence. But, to apply the reduce method, we need a function on which we apply it. So, we first created a multiply_the_sequence() function, which returns the product of two numbers. Then, we pass the function on reduce method as the first argument and simultaneously pass the sequence as the second argument. It first maps the first two elements of the sequence to the function and then multiplies each element from left to right to the result. After the sequence is covered, it yields us the product of the sequence.

Example 2: Applying reduce method on Lambda Function

from functools import reduce
final_result = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
print(final_result)

Output:

15

Explanation

As discussed in example 1st, we can also apply the reduce method to the lambda method. We need to pass the lambda function as the first argument and then the sequence as the 2nd argument. It yields us the sum by applying the sum to each element of the sequence.

Example 3: Performing string operation using reduce method

from functools import reduce

def concatenating_string(string1, string2):
  return (string1+string2)

tpl = ('P','Y','T','H','O','N','P','O','O','L')
final_string = reduce(concatenating_string,tpl)
print(final_string)
print(type(final_string))

Output:

PYTHONPOOL
<class 'str'>

Explanation

In the above example, we have performed a concatenation operation on the string using reduce method on a tuple object. This returns us the final string after concatenating each element from the sequence.

Example 4: Reduce method on dictionaries

from functools import reduce

def concatenating_string(string1, string2):
  return (string1+string2)

tpl = {'i':'00','j':'01','k':'02','l':'03'}
final_string = reduce(concatenating_string,tpl.values())
print(final_string)
print(type(final_string)

Output:

00010203

Explanation

So, we followed the same step as discussed above in the above example. Moreover, we accessed values of dictionaries using the value() method and then passed it as the argument for the reduce function.

Example 5: Flatten List using Reduce methods

So, as we already know, python doesn’t have the concept of an array. It stores the series of data in a list. However, sometimes we have a nested list of data in python, and we need to flatten it. There are many ways of doing that. One of them is using reduce function. Let’s see how we can do it using reduce function.

from functools import reduce

nestedlist = [ [1, 2, 3, 4], [5,6,7,8], [9,10,11,12]]
flatlist = reduce(lambda a,b:a+b, nestedlist)
print(flatlist)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Explanation

In the above example, we first created a nested list and then used that inside reduce function along with a lambda function defined. However, here the “+” operators act as the concatenation operator due to the presence of the nested list. So, it takes arguments from the nested sequence and appends them in an empty list.

Example 6: Reduce method on DataFrame

We can also use the reduce method on the DataFrame object. To do that, we need to pass the index position of the dataframe as the argument of reduce function along with the function as the first argument. Let’s see an example.

import pandas as pd
from functools import reduce

record1 = pd.Series({'i':4,'j':1,'k':2,'l':3})
record2 = pd.Series({'i':10,'j':11,'k':12,'l':13})
record3 = pd.Series({'i':20,'j':21,'k':22,'l':23})
record4 = pd.Series({'i':30,'j':31,'k':32,'l':33})

# Creating dataframe
df = pd.DataFrame([record1,record2,record3,record4],index = ['0','1','2','3'])
print(df)

def multiply_the_sequence(num1,num2):
  return (num1 * num2)

product = reduce(multiply_the_sequence,df.iloc[0])
print()
print(product)

Output:

    i   j   k   l
0   4   1   2   3
1  10  11  12  13
2  20  21  22  23
3  30  31  32  33

24

Example 7: Check all values of array are true using functools reduce

from functools import reduce

def check_values(arg1,arg2):
  if arg1 != True or arg2 != True:
    return 1

lst = [True, True, True, False, False, True]

val = reduce(check_values,lst)
if val == 1:
  print('Not all values are true')
else:
  print("All the values are true")

Output:

Not all values are true

Explanation

In the above example, we first created a function that checks the values of the argument and then returns whether they are true or not. Then, we print the output accordingly.

Alternative to Reduce() Method

Although the functools.reduce() method can be convenient and have a high scope. There could be another alternative too. To avoid it, we can simply use a function within a “for” loop. We will use the following block of code to do that.

result = start
for x in iterable:
    result = function(result, x)

Let’s see an example, an alternative to Example 6, which checks values for an array.

lst = [True, True, True, False, False, True]
result = 0
for x in lst:
    result = check_values(result, x)
if val == 0:
  print('Not all values are true')
else:
  print('All values are true')

Output:

Not all values are true

FAQs on FuncTools Reduce

Q1) Is functools reduce similar to an array.reduce() in JS?

Yes, we functools.reduce() method in python is similar to array.reduce() function in JS.

Conclusion

So, today in this article, we have taken a quick overview of the functools module. We have seen how we can use it to manipulate the functioning of any function. For that, we have seen different available functions that help us in doing that. We have also seen demonstrations over their work to get a clear understanding of them. I hope this article has helped you. Thank You.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments