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

Timothy Comeau
Timothy Comeau
3,710 Points

Stuck 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

Hi 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

Did you try using a for loop like the challenge recommends?

Timothy Comeau
Timothy Comeau
3,710 Points

Yes 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
Kenneth Love
Treehouse Guest Teacher

Timothy Comeau That's a great start but there are a couple of problems in it.

  1. 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.
  2. On line 3, you're adding the current item in the list to itself. So if item #1 is 2, line 3 just calculates 4.
  3. 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!