Python reduce function

This is an interesting short cut function when you want to process list items recursively.

This function takes two arguments in as input, one function name that you want to apply on list and second the list itself.

In python3 reduce is available in func_tools module. Typical syntax to invoke this is reduce(function_name, list_of_items) and it returns you a final value.

Here is how it works

  1. Initial function is called with first two items of the list to do some operation on these items.
  2. Then operation function is called again and again with arguments “result is last execution” and next item in list.
  3. This process repeats till the end of list and then final output value is returned from reduce() function.

In simple words, think of sharpening a pencil ✏️. You keep rotating pencil till you get a pointed lead. Rotation function on circumference of pencil in sharpener gives you finally a pointed lead.

Here is an example:


#!/usr/bin/python3

from functools import reduce

# Add two numbers
def add_num(a,b): return a + b

# Multiply two numbers
def multi(a,b): return a*b

# List of numbers
numbers = [1, 2, 3, 4, 5, 6]

# This is what following reduce using add_num will do
# 1+2=3 3+3=6 6+4=10 10+5=15 15+6=21

print(reduce(add_num, numbers))

# This is what following reduce using multi will do
# 1*2=2 2*3=6 6*4=24 24*5=120 120*6=720

print(reduce(multi, numbers))

Output:


./reduce.py 
21
720