Skip to main content

What Is REDUCE In Python

Before jumping on to what is reduce, let’s have a quick look at the lines below

import operator sum = 0
for n in [1,2,3]:
   sum = sum + n
print(sum)

You got it right. Here we are taking a collection having three numbers and summing them up.

As such, there is nothing wrong with this code but, of course there is a big room for optimization with respect to the number of lines of code we have written, just go get summation.

Now the question is, how can we optimize? How can we reduce the number of lines and achieve the same result?

Well, the answer is reduce function.

What is reduce?

Reduce is a function in Python provided by functools. This function takes a collection of values, performs some operation by calling a function and then returns a single value as an output. For example, you can give multiple values as input and perform mathematical calculations on them, you can perform operations on multiple strings, etc.

Ways to use reduce

There are two ways you can use reduce:

Way 1: With pre-defined function

from functools import reduce from operator import add
print(reduce(add,[1,2,3]))

Way 2: With lambda function

print(reduce(lambda a,b:a+b,[1,2,3))

Conclusion

You can see the number of lines got reduced to a single line with just one method call.

If you are convinced by this magic, make sure to watch out the recording of this feature on my YouTube channel:



Comments