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 Python Basics (Retired) Putting the "Fun" Back in "Function" Functions

Nathan Clevenger
PLUS
Nathan Clevenger
Courses Plus Student 17,759 Points

Python Basics - "Putting the 'fun' back in 'function'" Code Challenge

Can someone help me on this? I can't seem to get anything to pass.

Make a function named add_list that adds all of the items in a passed-in list together and returns the total. Assume the list contains only numbers. You'll probably want to use a for loop.

Here's my code:

def add_list(list):
    sum = 0
    for i in list:
      sum += i

Thanks!

1 Answer

Joseph Kato
Joseph Kato
35,340 Points

Hi Nathan,

It looks like all you need to do is return the calculated sum after the for-loop finishes.

(Also, it's generally considered good practice to avoid using built-in names as your own variable names.)

Nathan Clevenger
Nathan Clevenger
Courses Plus Student 17,759 Points

So I added:

def add_list(list):
    sum = 0
    for i in list:
      sum += i

return sum

but it didn't work. I still get - Bummer! Try again!

Which built in variable name are you referring to? Sum? I used 'total' the first few attempts but that didn't work. I only changed to sum by another example I found a python forum.

Joseph Kato
Joseph Kato
35,340 Points

You want to return the sum after the for-loop (not after each iteration). For instance:

def add_list(lst):
    total = 0
    for i in lst:
      total += i
    return total

And, yes, sum and list are built-in names. In fact, you can use sum like this:

def add_list(lst):
   return sum(lst)