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

Shawndee Boyd
Shawndee Boyd
6,002 Points

Make a function named add_list that adds all of the items in a passed-in list . I am completely befuddled. Please help.

list = [1, 2, 3]

def add_list():

3 Answers

Okay. It is a bit hard challenge. But possible to solve. First python function. You can define Python function

def add_list():

Next passing in list. Meaning you are passing in a list to the defined Python function.

If you want to pass-in variable or list, you will have to do in the braces next to function name. Something like this.

def add_list(variable):

Passing in list to Python function looks like this: I assume list_num is a list

def add_list(list_num):

To add all items in a list, you can use sum() function. In Python, if list items are integers or float you can use sum() function to add all of them together.

So final version of this program looks like this:

def add_list(list_num):
      return sum(list_num)

I hope it helps.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You can also do it without using sum().

Teacher, you mean using for loop?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Karthikeyan Palaniswamy Yeah, exactly. Have a counter variable that you start at 0 and increment with each item in the list. Ideally you'd solve this challenge without using sum() since we didn't talk about sum() in the lesson.

Yes teacher Kenneth Love. We can achieve the desired result that way too. Thanks!

When would you release next Python course? I can't wait to start studing Python more!

Shawndee Boyd
Shawndee Boyd
6,002 Points

I really thank you all for your help. I realized from your posts that I forgot about using return. Again, thank you!

Welcome Shawndee Boyd

Eddie Flores
Eddie Flores
9,110 Points

Here's the looped version.

def add_list(items_list):
  total = 0
  for item in items_list:
    total = total + item
  return total

def summarize(items_list):
  list = str(items_list)
  total = 0
  for item in items_list:
    total = total + item
  return "The sum of {} is {}.".format(list,total)