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 trial

Python

Why does this not work?

I am going through the python Code Challenge: Functions where it asks:

"Make a function named add_list that takes a list. The function should then add all of the items in the list together and return the total. Assume the list contains only numbers. You'll probably want to use a for loop. You will not need to use input()."

I got a bit stumped and found the right answer(s), but I am wondering why my code doesn't work for the first part:

#add_list takes a list
def add_list(list):
   #num breaks it up into pieces
   for num in list:
   #add becomes the sum of the pieces
   add = sum(num)
   #returns the summation
   return add

A google search suggested that I need an iterable term to use sum. Perhaps that's the part I'm not quite understanding? Does sum need a list, not the pieces fed by a for-loop? Something more like:

def add_list(list):
   add = sum(list)
   return add

Thanks for any answers, so far learning code is a ton of fun!

Sorry for the weird formatting on my question...not sure how to fix that.

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Your first code sample doesn't have add defined anywhere and you're calling sum() on an integer (since the iterable is full of integers). You need to start with 0 and add each integer to it.

Thanks for the speedy response Kenneth!