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

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!