Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
Quite often we have an iterable that has an answer in it. How do we get that answer out, though? Let's look at `reduce()` and the concept of recursion.
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.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up-
Joel Sprunger
5,448 Points1 Answer
-
Ross Coe
5,061 PointsCan you explain how an empty list can be passed in long_total and that's not seen as None?
Posted by Ross CoeRoss Coe
5,061 Points1 Answer
-
amalsree
2,396 Points2 Answers
-
Qian Chen
33,579 Points0 Answers
-
Sahar Nasiri
7,454 Points2 Answers
-
Sahar Nasiri
7,454 PointsTotal
Posted by Sahar NasiriSahar Nasiri
7,454 Points2 Answers
-
James N
17,864 Points1 Answer
-
PLUS
Bikram Mann
Courses Plus Student 12,647 Points4 Answers
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up