Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

What Is the reduce() Function?

Give Feedback

In this lesson, you’ll learn how to use the reduce() function (or functools.reduce() in Python 3), which is one of the functional programming primitives (or building blocks) available in Python. It takes a function, a sequence (or iterable), and an optional initial value.

You’ll walk through how you can use the reduce() function with the data set that you’ve been using in this course to reduce a sequence to a sinlge output value by applying a function repeatedly in order to output a single value.

Comments & Discussion

breaves on March 29, 2020

So you’ve basically defined the function def f(acc,val): return acc+val[‘age’]

So each item of the sequence is always applied to the SECOND argument of the function, right? Could as well be def f(x,y): return x+y[‘age’] and it’s basically calling for s in sequence: x=f(x,s) return x

right?

Roy Telles on July 24, 2020

If I’m not mistaken, reduce() can be viewed as doing the for loop iterations for us:

We can expand the reduce() function to be something like:

def total_age(val, acc=0):
    for item in val:
        acc += item['age']

    return acc
  • acc=0 is what reduce() does when we pass the optional initial value 0 to it
  • acc += item['age'] is what reduce() does for us, at its core
  • return acc is our ultimate value at the end of our iterations

Become a Member to join the conversation.