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

John Rugh
John Rugh
7,784 Points

Stuck on Python challenge Stage 5

Here is the question: "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."

list = []

def add_list(list) add_list.append(list)

Above is what I have thus far. Lost..

2 Answers

Charlie Thomas
Charlie Thomas
40,856 Points

First of all don't bother creating a blank list. Then define your function as you have done before after that inside you function you need to create a variable to store the total of the numbers, then a for loop that cycles through the numbers and adds them to total and finally return the total variable. For example:

def add_list(list):
    total = 0
    for num in list:
        total = total + num
    return total
Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Also, as a note to both of you (and everyone else), not the best idea in Python to make variables named for different data types. You don't usually want a variable named list or str. To see why, try this in a Python interpreter:

>>> list('hello')
>>> list = ['a', 'b', 'c']
>>> list('goodbye')
Ricky Catron
Ricky Catron
13,023 Points

Had to chuckle at this. I remember one time I wrote a file and called it MD5.py then tried to import the MD5 library............couldn't figure out why the darn thing crashed until a friend laughed at me.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Ricky Catron every single one of us has or will do it. It's just so easy, since Python doesn't actually protect keywords or variable/function names. I take no responsibility for what any one does with the following:

>>> True, False = False, True
Ricky Catron
Ricky Catron
13,023 Points

I am definitely going to use that to mess with a professor one of these day!