reduce()
The reduce()
function returns an aggregated value that results from the application of a function to an iterable. The function is applied to the first pair of items in the iterable and the resulting value is then used with the next item in the sequence, this process repeats through item n.
Syntax
reduce(func_name, iterable, initializer)
The func_name
is the function to be applied to the iterable and can be a lambda function or the name of any defined function. The iterable
contains the items, such as a list, the function will act on. The initializer
is an optional parameter that provides the ability to substitute an initial value for the first calculation. With the initializer
set, the first calculation will be between the initializer
value and the first item in the sequence in lieu of the first and second items of the sequence.
Example
The following example uses reduce()
to sum all the values in the nums
list and add this value to an initial sum start
:
from functools import reducestart = 30nums = [x for x in range(10)]print(reduce(lambda x, y: x + y, nums, start))# Output: 75
Codebyte Example
reduce()
can be used to return the minimum value within a list:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours