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 trialBen Muresan
265 PointsAdding items in a list
My code here doesn't seem to add up the items in the list. I got it before, and now I cant seem to duplicate what I did last time. Any ideas?
# 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 (x):
sum = 0
for item in x:
sum = sum + x
return sum
2 Answers
Dan Johnson
40,533 Pointsitem is an individual element, and x is the entire list. Switch to this:
def add_list (x):
sum = 0
for item in x:
sum = sum + item
return sum
kirkbyo
15,791 PointsHi Ben,
When adjusting the values of your sum
variable, instead of adding sum
to x, you can use the +=
operator.
sum += x
Also, you can't add x
to the sum
variable, because x is the list the challenge is going to pass to your function. Instead you will want to use your item
from your for loop, because it will be each number from your list. For example:
The task will pass you a list that will resemble this
[12, 45, 23, 4, 189]
and then you're for loop will loop over every number and that number can be referred to as item
or whatever you decided to call it.
for item in x:
print(item)
The first time the loop runs item
will be equal to 12, the second time it will be equal to 45, ect...
def add_list (x):
sum = 0
for item in x: # Item will be each number from your list
sum += item # += Operator to add the item to the sum variable
return sum
I hope this helped. If you have any other question don't hesitate to ask.
Ozzie