The reduce() Function: Overview – Real Python (original) (raw)
In this section, you’ll discover another basic of functional programming: how to use the reduce()
function to transform data structures.
We’ll take an example data set represented using an immutable data structure from the previous lessons in this course, and then we’ll create a reduced or derived output from that data using Python’s built-in reduce()
function.
reduce()
(or functools.reduce()
in Python 3) is one of the functional programming primitives (or building blocks) available in Python. It’s useful in a number of contexts.
Later in this section, you’ll see how the reduce()
function lets you group your data set into arbitrary categories. You’ll also learn about Python’s defaultdict class defined in the collections
module, as well as some useful helpers in the itertools
module, like itertools.groupby
.
00:00 Hey there! This is Dan Bader, and this is another part in my Python functional programming series, where we talk about “What is functional programming, anyway?” and where we can learn some of the functional programming primitives in Python, like the filter() function, the map() function—and in this video, we’re going to talk about the reduce() function.
00:17 We’re working with a simple data set of scientists and their birthdates and stuff like that, and we’re transforming it in interesting ways using functional programming principles. In this video, I want to talk about another functional programming primitive.
00:33 That is the reduce() function. Because I’m on Python 3, here, I need to first import the reduce() function from the standard library.
00:41 I believe on Python 2, you’d be able to just go reduce() and that function will be a built-in that’s available in the global namespace, but because I’m in Python 3, I need to actually go from functools import reduce. Yeah.
00:59 Then, we can take a look at the docstring here again. I love this docstring because I still remember the first time I was learning how some of these functional primitives work—in another programming language at the time—and just reading the definition of the reduce() function in, like, my first year of computer science education. I was just sitting there, like, “I have no idea what you’re talking about!” And well, I hope you don’t feel the same, but if you do, then don’t worry because you can figure this stuff out.