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 trialTony Brackins
28,766 PointsI'm lost, please help. Make a function named add_list that adds all of the items in a passed-in list together and return
This is what I've got so far. I watched all the videos, I've followed along but I'm stuck here. Please help:
passed_in_list = [1, 2, 3]
def add_list():
for item in passed_in_list:
passed_in_list
4 Answers
Marko Koron
20,658 PointsI don't know the concrete problem but first of all I would define the function this way:
def add_list(sum_list):
for item in sum_list:
...
then you call the function like this add_list(passed_in_list). But for your code also would work. Regarding your problem, you did start OK with the statement for item in passed_in_list, now think of what did you write after. You are looping a list, so are looking for an item on the second line, not the list. And what do you need to do with this items? Add them together, so you need a variable that will store the sum, and in the for loop it will store the the sum of all the items one by one (don't forget that you need to add the value that this variable is holding with the every new item.). After the loop ended you simply return the variable holding the sum.
Marko Koron
20,658 PointsYou need to initialize the variable sum like this, sum = 0, or you will get a referenced before assignment error(remember that you are using the value of this variable in the summation "sum = sum + item", you cannot have "sum = undefined + item")
Tony Brackins
28,766 PointsI'm sorry, I'm still not understanding.
I know that this is the answer and have a few questions: list=[1,2,3]
def add_list(list): sum = 0 for num in list: sum = sum + num return sum
b= add_list(list) print(b)
for "sum = 0", where did this come from?
Like, how would I know to make this statement?
Thanks,
Tony
Tony Brackins
28,766 PointsOk got it. Thanks!