functools.reduce() takes a function and an iterable. The function, though, takes two arguments. The first time it runs, the two arguments will be the first two items in the iterable. Every time after that, the first argument will be the result of the last time the function was run. The second argument will be the next value from the iterable. When the iterable is out of items, reduce() will return whatever the function returned last.

Think about adding up all of the numbers in a column. You add the top two, then add the third number to the sum you got from the first two. Then you add the fourth number to the sum of the top three, and so on.

Calling a function over again from within itself is known as recursion and it's what makes reduce() able to do its job.

0:00

[MUSIC]

0:04

When you learn about
functional programming,

0:07

you generally learn about three tools,
map, filter, and our next one, reduce.

0:11

Often you'll even here map and reduce used
together, but we'll get to that later.

0:16

First though, let's talk about reduce
on its own and a concept we've used but

0:20

never really focused on.

0:22

Reduce takes a function and an iterable,

0:24

and then applies the function to
the first two items in the iterable.

0:28

Then it takes the return value of that
function and applies the function again

0:32

with that originally returned value and
the next item in the iterable.

0:36

Eventually, of course,
the iterable runs out of values, and

0:39

reduce returns the last value
that came out of the function.

0:42

When we talk about a function that
repeatedly calls itself to get new values

0:45

we say that the function is recursive.

0:48

We've written a few recursive
functions in the past.

0:50

It's a very useful technique.

0:52

Okay let's go see how to use reduce.

0:55

So reduce let's get
an answer from an iterable.

1:00

So we can be like,
hey what's the sum of all these things?

1:03

Although then we can use sum.

1:04

[LAUGH] Or we can do what's all
these things multiplied together?

1:07

Or whatever.

1:09

So let's do a simple function
to play with reduce, and

1:13

then we'll do something
a little bit more complicated.

1:15

So let's just do def product, and it's
gonna take two variables, x and y, and