(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!
Python reduce() function
Updated on Nov 09, 2019
reduce() function accepts a function and a sequence and returns a single value calculated as follows:
- Initially, the function is called with the first two items from the sequence and the result is returned.
- 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:
reduce(function, sequence[, initial]) -> value
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:
from functools import reduce # only in Python 3
Here is an example which adds all the items in the list.
1 2 3 4 5 6 7 8 9
>>> >>> from functools import reduce >>> >>> def do_sum(x1, x2): return x1 + x2 ... >>> >>> reduce(do_sum, [1, 2, 3, 4]) 10 >>>
Try it out:
from functools import reduce def do_sum(x1, x2): return x1 + x2 print(reduce(do_sum, [1, 2, 3, 4]))
reduce() call perform the following operation:
(((1 + 2) + 3) + 4) => 10
reduce() call is functionally equivalent to the following:
1 2 3 4 5 6 7 8 9 10 11
>>> >>> def my_reduce(func, seq): ... first = seq ... for i in seq[1:]: ... first = func(first, i) ... return first ... >>> >>> my_reduce(do_sum, [1, 2, 3, 4]) 10 >>>
Try it out:
def do_sum(x1, x2): return x1 + x2 def my_reduce(func, seq): first = seq for i in seq[1:]: first = func(first, i) return first print(my_reduce(do_sum, [1, 2, 3, 4]))
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!