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!
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
Gary Gibson5,011 Points
Why is .append() not giving me the same answer as +=?
The code challenge is to get all the courses in the values into a new list. This is the code that works for the challenge:
def courses(dict_teachers): course_list =  for courses in dict_teachers.values(): course_list += courses return course_list
This is the code I initially wrote which failed:
def courses(dict_teachers): course_list =  for courses in dict_teachers.values(): course_list.append(courses) return course_list
course_list += courses work and
Steven Parker225,726 Points
If you were to try printing out the returned lists in each case using the workspace, you'll notice:
+= extends the list with the contents of the new list (
[a, b, c, d])
.append() extends the list by adding the new list as a single new item (
[a, b, [c, d]])
This is discussed starting around 5:30 in the Lists video of the Python Basics course.
If you wanted to, you could make .append() work with an additional loop:
def courses(dict_teachers): course_list =  for courses in dict_teachers.values(): for each_course in courses: course_list.append(each_course) return course_list
But I think your first example is a better solution.