Python reduce() function


(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


The reduce() function accepts a function and a sequence and returns a single value calculated as follows:

  1. Initially, the function is called with the first two items from the sequence and the result is returned.
  2. The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps repeating until there are items in the sequence.

The syntax of the reduce() function is as follows:

Syntax: reduce(function, sequence[, initial]) -> value

When the initial value is provided, the function is called with the initial value and the first item from the sequence.

In Python 2, reduce() was a built-in function. However, in Python 3, it is moved to functools  module. Therefore to use it, you have to first import it as follows:

Here is an example which adds all the items in the list.

This reduce()  call perform the following operation:

The preceding reduce() call is functionally equivalent to the following:

However, the reduce() call is much more concise and performs significantly better than the for loop.


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


One thought on “Python reduce() function

  1. Alex

    Thanks! Very clear explanation of the reduce function. Now I finally learned what it does ))Already many years developing software but had not that much experience with functional programming. And what does this mysterious reduce function was always secret for me.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *