Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (Retired) Putting the "Fun" Back in "Function" Functions

functions challenge - stuck on first task

I can't really think of another way to word the code to receive the correct sum. I was able to somehow pass the first task with another code, but I was receiving an incorrect sum.

The error: list index out of range.

functions.py
# add_list([1, 2, 3]) should return 6
# summarize([1, 2, 3]) should return "The sum of [1, 2, 3] is 6."
# Note: both functions will only take *one* argument each.
def add_list(list):

    total = 0

    for i in list:
        total += list[i]

    return total 

2 Answers

deckey
deckey
14,630 Points

Hi Alec, the function was correctly set, but you are calling list[i] within the loop, which is wrong.

  • first loop pass, i = 1, so list[1] gets called - total becomes 2
  • second pass, i = 2, so list[2] gets called - total becomes 5
  • third pass, i =3 , so list[3] gets called which is 'out of index' as there are only 3 elements in the list.

So, what you need is just 'i' to be added to total, not list[i]

good luck!

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You don't need list[i] when you do for i in list:. i is the current item for this step in the list. Look at this:

my_list = ['a', 'b', 'c']

for letter in my_list:
    print(letter)

This would print

a
b
c

because each time the loop loops, letter is changed to the next item in my_list.

Thank you for explaining it in such a simple way there. It makes a lot of sense!