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

Help making a function

Make a function named add_list that takes a list. The function should then add all of the items in the list together and return the total. Assume the list contains only numbers. You'll probably want to use a for loop. You will not need to use input().

Please see code attached

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(a_list):
  a_total = 0

  for item in a_list:
    a_total =  item[0] + item[1] + item[2]
    return a_total

Your for loop is going to go through each item until it hits the end of your list. You do not need to slice it. By using a for loop you don't need to know the number of items in the list. The loop will run until it gets to the end. Additionally, you can use the += operator to add each item in the list together.

3 Answers

Mikael Enarsson
Mikael Enarsson
7,056 Points

A few points. First of all, this kind of for-loop goes through every item in "a_list", and stores the values in "item." That is, the first time it loops you have item = a_list[0], the second time item = a_list[1] etc. This function is supposed to take advantage of this and add lists of arbitrary length!

Secondly, currently the indentation of your "return" statement makes it trigger inside the for-loop, you'll have to change this so that the statement executes after the loop is done.

I hope that this is of help, and if not, ask and I can expand on it ^^

def add_list(nums): return sum(nums)

def add_list(nums): return sum(nums)

This is the simplest solution

  1. def add_list(nums) # it shows there is a list of numbers
  2. return sum(nums) # Calls the function to give the sum total of the numbers in the list