Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python The Lambda Lambada Reduce

Chris Grazioli
Chris Grazioli
31,225 Points

I have no idea what the add function/method does, anyone care to explain it

In Functional Python, none of the videos actually covered the add function/method. I would greatly appreciate someone taking a stab at explaining it.

Also the concept of Map() versus Reduce() isn't really shaking out for me either... they seem to do the same thing? Whats the difference and what would be the use case for either?

1 Answer

Steven Parker
Steven Parker
218,596 Points

:point_right: The challenge says add is a function that will "add two numbers together".

If you wrote it yourself, it would probably look like this:

def add(a, b):
    return a + b

Since it is already available in the operator module, they just have you import it.

Then map takes a function which itself takes one argument, and applies it to each item in a list, and returns the resulting list. For example:

def add5(a):
    return a + 5;
mylist = map(add5, [1, 2, 3, 4])  # mylist will be [6, 7, 8, 9]

On the other hand, reduce takes a function which itself takes two arguments, and applies that to an accumulator and each list item, and then returns the accumulator (a single value). For example:

total = reduce(add, [1, 2, 3, 4])  # total will be 10

Make sense now?