The Reduce Function in Python


In Python, the reduce() function is declared in the functools. And it has the following function signature:

reduce(method, data, initial_value);

The reduce() function will iterate over the data array (or list), and accumulate a value (set to initial_value first) using the given function which has the following signature:

def reducer_method(accumulated_value, current_value):
   pass

For example, to sum up all the values from 1 to 100, you can use this:

from functools import reduce
reduce(lambda s, cur: s + cur, range(101), 0)

As we can see, the reducer function for sum is passed as a lambda function, which is essentially the same as:

def reducer_sum(s, cur):
   return s + cur

The reduce() function in Python allows you to do one-liner without need to write a loop.

How is reduce() implemented in Python?

The reduce() function is as simple as the following:

def reduce(reducer, data, value):
   cur = value
   for i in data:
      cur = reducer(cur, i)
   return cur

–EOF (The Ultimate Computing & Technology Blog) —

231 words
Last Post: The Combination Function and Iterator using Depth First Search Algorithm
Next Post: How to Solve SMTP: Could Not Authenticate using Gmail + PHPMailer?

The Permanent URL is: The Reduce Function in Python (AMP Version)

Leave a Reply