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 trialDANIEL RILEY
423 PointsI'm getting the right return but i'm still not passing correctly... how do i convert the list to a string using my code?
x = [1, 2, 3]
def add_list(x):
for num in x:
sum_of_list = sum(x)
return sum_of_list
def summarize(x):
return "The sum of {} is {}".format(x, sum(x))
Kenneth Love
Treehouse Guest TeacherWhy are you sum
ing the list for every item in the list? sum()
adds the contents of a list together, so you don't need to do it repeatedly, just once.
1 Answer
Nazmus Sarwar
5,625 PointsEverything in python is an object, and thus you can use this special method for strings to join a list into a string.
",".join(x)
So if for say
x = [1, 2, 3, 4, 5]
It would join every element by a comma. However, this method only naturally joins strings together, not integers. So you would need to use list comprehensions.
return "The sum of {} is {}".format(", ".join(str(num) for num in x), sum(x))
inside of your summarize function.
DANIEL RILEY
423 PointsThank you I believe I understand better now.
DANIEL RILEY
423 PointsDANIEL RILEY
423 Points**** UPDATED
def add_list(x): for num in x: sum_of_list = sum(x) return sum_of_list
def summarize(x): y = str(x) return "The sum of {0} is {1}".format(y, add_list(x))