Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialShawndee Boyd
6,002 PointsMake a function named add_list that adds all of the items in a passed-in list . I am completely befuddled. Please help.
list = [1, 2, 3]
def add_list():
3 Answers
nvcxnvkldsjaklfds
Courses Plus Student 5,041 PointsOkay. It is a bit hard challenge. But possible to solve. First python function. You can define Python function
def add_list():
Next passing in list. Meaning you are passing in a list to the defined Python function.
If you want to pass-in variable or list, you will have to do in the braces next to function name. Something like this.
def add_list(variable):
Passing in list to Python function looks like this: I assume list_num is a list
def add_list(list_num):
To add all items in a list, you can use sum() function. In Python, if list items are integers or float you can use sum() function to add all of them together.
So final version of this program looks like this:
def add_list(list_num):
return sum(list_num)
I hope it helps.
Shawndee Boyd
6,002 PointsI really thank you all for your help. I realized from your posts that I forgot about using return. Again, thank you!
nvcxnvkldsjaklfds
Courses Plus Student 5,041 PointsWelcome Shawndee Boyd
Eddie Flores
9,110 PointsHere's the looped version.
def add_list(items_list):
total = 0
for item in items_list:
total = total + item
return total
def summarize(items_list):
list = str(items_list)
total = 0
for item in items_list:
total = total + item
return "The sum of {} is {}.".format(list,total)
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherYou can also do it without using
sum()
.nvcxnvkldsjaklfds
Courses Plus Student 5,041 Pointsnvcxnvkldsjaklfds
Courses Plus Student 5,041 PointsTeacher, you mean using for loop?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherKarthikeyan Palaniswamy Yeah, exactly. Have a counter variable that you start at 0 and increment with each item in the list. Ideally you'd solve this challenge without using
sum()
since we didn't talk aboutsum()
in the lesson.nvcxnvkldsjaklfds
Courses Plus Student 5,041 Pointsnvcxnvkldsjaklfds
Courses Plus Student 5,041 PointsYes teacher Kenneth Love. We can achieve the desired result that way too. Thanks!
When would you release next Python course? I can't wait to start studing Python more!