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 trialTimothy Comeau
3,710 PointsStuck on Python function Challenge Q 1
I'm stuck on what the right approach is for this question. I know this works to get the required answer, but isn't structured according to expectation.
How do I split the list into individual segments and add them together?
example_list=[1,2,3]
aw = example_list[0]
bw = example_list[1]
cw = example_list[2]
def add_list():
ans=int(aw+bw+cw)
print(ans)
add_list()
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Timothy,
Inside your function you need a variable that is going to store the sum and then each time through the for loop you're going to add a number from the list to your sum variable. Then you want to return that sum.
def add_list(lst):
sum = 0
for num in lst:
sum = sum + num
return sum
Adam N
70,280 PointsDid you try using a for loop like the challenge recommends?
Timothy Comeau
3,710 PointsYes I tried something like
def add_list(example_list):
for item in int(example_list):
item + item
add_list()
but the most I could get was an output of 2, 4, 6, i.e. item + item worked individually
Kenneth Love
Treehouse Guest TeacherTimothy Comeau That's a great start but there are a couple of problems in it.
- You're trying to convert a list to an integer on line 2. Each item in the list is already an int, and lists don't turn into ints anyway (how would you do that?) so that's gonna fail and throw an exception.
- On line 3, you're adding the current item in the list to itself. So if item #1 is
2
, line 3 just calculates4
. - And, lastly, on line 5 you call the function. This is good for when you're testing, but isn't needed to pass my code challenges.
You're making great progress! Keep it up!
Timothy Comeau
3,710 PointsTimothy Comeau
3,710 PointsThanks, it works