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 Collections (2016, retired 2019) Lists Growing Lists

fahad lashari
fahad lashari
7,693 Points

How is this any different from list.append()?

Just wondering as I had completed the python collections not long ago

Steven Parker
Steven Parker
231,269 Points

What is it you are comparing to list.append()?

fahad lashari
fahad lashari
7,693 Points

Hi I am talking in regards to where he used += to add things into the list. Just wondering why he would use that instead of append and extend.

kind regards

2 Answers

Steven Parker
Steven Parker
231,269 Points

It depends on what you are adding to the list.

For single items, .append(), .extend(), and += all do the same thing.

But if the item being added is another list, there's a difference. Both .extend() and += will add the elements from the new list onto the other, but .append() will add the entire new list as a single element onto the other list.

Say for example, you had two lists each with 3 elements. If you combine them with .append() you will have a list with 4 elements, and the last element will itself be a list of 3 elements. But if you combine them with either of the other methods you will get a list of 6 individual elements.

Steven Parker
Steven Parker
231,269 Points

The inner list, yes. And the same with extend. Both would still be unwrapping the outer list and adding the elements individually.